problems with photoimage and tkinter

Eric Brunel eric.brunel at pragmadev.com
Thu Feb 28 05:13:28 EST 2002


Hi Seth,

Seth Jones wrote:
> Hi, I'm looking for some help using images in tkinter. I've spent hours
> with it, and I can't
> seem to get anything working. Well, I have something. The following code
> is from the Python Imaging Library 'painter.py'.. This is the minimum
> necessary to display an image on the canvas.
> The line
> 
>                 #self.tile[(x,y)] = box, tile
> 
> must be uncommented in order for this code to work, and for the life of
> me, I can't imagine why. 
[snip]

You ran into a bug in Tkinter: when you create an image (either via 
BitmapImage or PhotoImage) and you attach it to a widget (Button, or 
Canvas, or whatever), for some reason, the reference counter for the 
BitmapImage or PhotoImage instance is *not* increased. So, using a simple 
example, here is what happens:

def f(canvas):
  # Image creation and recording in "img" -> reference counter is 1
  img = PhotoImage(...)
  # Creation of image in canvas -> reference counter is *not* increased, so
  # it's still 1
  canvas.create_image(..., image=img ...)

# End of function f => img goes out of scope => reference counter for image
# is decremented => falls to 0 => image is destroyed!!!
# When canvas will be updated on screen, the image won't show, since it has
# been destroyed...

So here is probably one of the purposes of the line you spotted: keep 
another reference on the image so that it won't be destroyed once the 
method is finished... If I wanted the above code to work, I would create a 
global variable for example, just to put the image in it.

BTW, for the general audience, this bug exists at least since Python 1.5. I 
found it very confusing the first time I encountered it, and I do 
understand why other people find it quite confusing too. Even if I didn't 
personally see it, I suppose this is an issue that appeared more than once 
in c.l.py. Why is this bug still not corrected? Anybody maintaining Tkinter 
out there?

HTH, & TIA
 - eric -




More information about the Python-list mailing list