[Tutor] Tkinter pass-by-reference query
Alan Gauld
alan.gauld at freenet.co.uk
Sat May 20 14:12:23 CEST 2006
> While attempting to add images to a canvas programmatically, I wrote
> the following:
> for i in os.listdir('./icons/terrain'):
> ... img = PhotoImage(file='./icons/terrain/'+i)
> self.terrainScreen.create_image(int(self.terrainScreen["height"])-50,
>
> (int(self.terrainScreen["height"])-50),
> image=img,tag=None)
> 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.
Everything in Python is passed by reference. The issue here is that
one the reference goes out of scope the image object gets garbage
collected!
> In other words, unless there is a permanent `img' variable, the data
> disappears.
>For example (replace w\ your own gifs):
>>> from Tkinter import *
>>> root = Tk()
>>> terrain = Canvas(root,width=50,height=50)
>>> img = PhotoImage(file='MapEditor/icons/terrain/desert.gif')
>>> terrain.create_image(0,0,image=img)
>Works beautifully, eh?
>>> img = PhotoImage(file='MapEditor/icons/terrain/water.gif')
> Doh! Now it disappears!
You've crated a new image object but you need to pass that to
the canvas, or more easily...
Try configuring the file property of the image:
img.configure(file='MapEditor/icons/terrain/water.gif')
That changes the file used by the image object that is being
displayed.
The image object is a placeholder within your GUI for displaying
graphics. You only need one object because you are onmly displaying
one image (at a time) in the GUI.
HTH,
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list