Tkinter PhotoImage weirdness
fredrik at pythonware.com
Sat May 12 11:14:41 CEST 2001
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
> -------------- cut here --------------
> from Tkinter import *
> root = Tk()
> colorwheel = PhotoImage( file="ColorWheel.ppm" )
> butt = Button(root,
> # image = PhotoImage( file="ColorWheel.ppm" ))
> image = colorwheel )
> -------------- 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.
More information about the Python-list