Tkinter PhotoImage weirdness

Theodore D. Sternberg strnbrg at c532352-a.frmt1.sfba.home.com
Sat May 12 11:58:44 EDT 2001


Interesting.  Are there any other similar gotchas in Python?  This is very
surprising behavior.

And yes, I did state it backwards; the program as written work, moving the
^# is what makes the image disappear.

In article <5a7L6.1638$Yu6.405219 at newsc.telia.net>,
Fredrik Lundh <fredrik at effbot.org> wrote:
>Theodore D. Sternberg wrote:
>> Seemingly trivial modifications to the following program
>> cause the image to appear or, alterately, fail to appear.
>>
>> As written, only a blank button appears.  But remove the ^#
>> and instead comment out the line after, and the image (you'll
>> need to provide your own in a file ColorWheel.ppm) does
>> appear.
>>
>> -------------- cut here --------------
>> from Tkinter import *
>> root = Tk()
>> colorwheel = PhotoImage( file="ColorWheel.ppm" )
>> butt = Button(root,
>> #           image = PhotoImage( file="ColorWheel.ppm" ))
>>             image = colorwheel )
>> butt.pack()
>> root.mainloop()
>> -------------- cut here ---------------
>>
>> I'm stumped; why would this trivial difference matter?
>
>Are you sure you didn't get that backwards: on my box, the
>program works as written, but the image disappears if you use
>the inline variant.
>
>the reason for this is that Python's garbage collector doesn't
>understand that the image is in use by Tkinter, and happily
>removes the PhotoImage object when it's done with calling
>the Button constructor.  if you keep an extra reference to
>it (via a global, an instance attribute, etc), everything will
>work as expected.
>
>also see:
>
>    http://www.python.org/doc/FAQ.html#4.69
>
>Cheers /F
>
>
>





More information about the Python-list mailing list