Tkinter: image handling: bug or feature?

Jose' Sebrosa sebrosa at
Fri Jun 1 05:45:23 CEST 2001


I just figured out that this code

from Tkinter import *
class NotSoFunny(Toplevel):
    def __init__(self, master):
        Toplevel.__init__(self, master = master)
        #global my_img    #  <-- PAY ATENTION TO THIS LINE
        my_img = PhotoImage(file = 'my_image.gif' )
        Label(self, image = my_img, bg = 'yellow').pack()
if __name__ == '__main__':  (None).mainloop()

does *not* display the image, but it does if i uncomment the highlighted line
(global statement).  The problem seems to be that, at the time the mainloop()
is started, the reference to the image must be available to be displayed.

Another way to ge the image displayed is to preserve them in the instance

from Tkinter import *
class Funny(Toplevel):
    def __init__(self, master):
        Toplevel.__init__(self, master = master)
        #  --> NOW I USE self.my_img INSTEAD OF my_img <--
        self.my_img = PhotoImage(file = 'my_image.gif' )
        Label(self, image = self.my_img, bg = 'yellow').pack()
if __name__ == '__main__':  Funny(None).mainloop()

As far as I see, this happens with images only. I like to use local names to
everything I can (so the names are not available when mainloop is called) and
the widgets are displayed with no problem...

What's wrong with the images?

I would (wildly) guess that the problem is somewhere in the python-tk
interaction layer... somehow, when we set the image option of a label, the
python does *not* make another reference to the image, so it is lost when the
name is local. Perhaps something in the 
python -> command (string) for tk -> tk
sequence makes tk receive an instruction to display an image that it can't find

Or I'm simplly messing it all...


More information about the Python-list mailing list