Tkinter: image handling: bug or feature?

John Roth johnroth at ameritech.net
Sat Jun 2 10:22:02 EDT 2001


I believe this behavior is documented - one of the references I've
been inhaling recently stated that you **must** keep a reference
to an image around, or the displayed version will vanish when the
image is garbage collected.

If I had to guess as to why, I'd think it was because Tkinter doesn't
make a copy of the image anywhere - and once you get into Tk
itself, you're playing by its rules on references and garbage collection,
not Python's. If Tkinter kept its own reference, then other bad
things might happen in oddball cases.

John Roth


"Jose' Sebrosa" <sebrosa at artenumerica.com> wrote in message
news:3B170FD3.B98D5E51 at artenumerica.com...
>
> Hi,
>
> 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
> namespace:
>
> 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
> anymore...
>
> Or I'm simplly messing it all...
>
> Sebrosa





More information about the Python-list mailing list