Tkinter PhotoImage weirdness

Isaac To Kar Keung kkto at csis.hku.hk
Sat May 12 13:21:49 EDT 2001


>>>>> "Fredrik" == Fredrik Lundh <fredrik at pythonware.com> writes:

    Fredrik> the reason for this is that Python's garbage collector doesn't
    Fredrik> understand that the image is in use by Tkinter, and happily
    Fredrik> removes the PhotoImage object

Anyone know why this has to be this way?  Yes, I've looked at newsgroup
archive and FAQ, and I think that this question is bought up a few times.
Why we can't just have a reference in the Button, Label or Canvas object to
the PhotoImage object to prevent it from getting destroyed?  This is
especially strange when you look at the actual thing stored:

>>> from Tkinter import *
>>> a=Tk()
>>> img=PhotoImage(width=100, height=100)
>>> img
<Tkinter.PhotoImage instance at 8116570>
>>> l['image']
'135357808'
>>> '%x' % 135357808
8116570
>>> del img
>>> l['text'] = 'abc'
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "/usr/lib/python1.5/lib-tk/Tkinter.py", line 630, in __setitem__
    self.configure({key: value})
  File "/usr/lib/python1.5/lib-tk/Tkinter.py", line 623, in configure
    self.tk.call((self._w, 'configure')
TclError: image "135357808" doesn't exist

That is, Tkinter actually stores a 'pointer' there, but instead of storing a
Python pointer, it stored the string representing the address of the pointer
in decimal.  This is probably the strangest thing that we can have in a
language like Python where the language handles all the pointers.  Even in C
or C++, people dislike storing a pointer in an int variable.  Now we have
that in Python, and it store not an int, but a string.  How things can get
more wierd?

Regards,
Isaac.



More information about the Python-list mailing list