[Tutor] Tkinter pass-by-reference query

Kent Johnson kent37 at tds.net
Sat May 20 06:01:43 CEST 2006


Henry Finucane wrote:
> While attempting to add images to a canvas programmatically, I wrote
> the following:
> for i in os.listdir('./icons/terrain'):
> 	self.terrainScreen["height"] = str(int(self.terrainScreen["height"])+50)
> 	debug(self.terrainScreen["height"]+" height of terrainScreen",5)
> 	img = PhotoImage(file='./icons/terrain/'+i)
> 	self.terrainScreen.create_image(int(self.terrainScreen["height"])-50,(int(self.terrainScreen["height"])-50),
> image=img,tag=None)
> 
> I couldn't figure out why it didn't work, until I went in and played
> with Tkinter in the python shell, and I came to the conclusion that
> the reason nothing was displayed on the canvas was that images are
> passed by reference. In other words, unless there is a permanent `img'
> variable, the data disappears.

For some reason Tkinter doesn't keep a reference to the image you pass 
it. So when your reference goes out of scope, the image is 
garbage-collected and can no longer be displayed. The solution, as you 
have found, is to keep a reference to the image somewhere. It can be in 
a variable, or you could make a list of images.

Kent



More information about the Tutor mailing list