unsettling tkinter bug -- or is it just me?

Bob van der Poel bvdpoel at uniserve.com
Tue Jun 13 19:12:23 EDT 2000


Robert Roy wrote:
> 
> On Mon, 12 Jun 2000 18:14:36 -0700, Bob Lewis <bobl at tricity.wsu.edu>
> wrote:
> 
> >Consider the following code:
> >--------
> >
> >from Tkinter import *
> >
> >root = Tk()
> >img = PhotoImage(file='bobl.gif')
> >
> >def func():
> >    cnvs = Canvas(root, width=img.width(), height=img.height())
> >    cnvs.create_image(0,0, image=img, anchor=NW)
> >    cnvs.pack(side=TOP)
> >    Button(root, text='Quit', command=root.quit).pack()
> >
> >func()
> >root.mainloop()
> >--------
> >This runs just fine: It creates a root toplevel with "bobl.gif" displayed
> >in it and a "Quit" button.
> >
> >Now we make one wafer-thin change: Move the the "img =" inside "func()":
> >--------
> >from Tkinter import *
> >
> >root = Tk()
> >
> >def func():
> >    img = PhotoImage(file='bobl.gif')
> >    cnvs = Canvas(root, width=img.width(), height=img.height())
> >    cnvs.create_image(0,0, image=img, anchor=NW)
> >    cnvs.pack(side=TOP)
> >    Button(root, text='Quit', command=root.quit).pack()
> >
> >func()
> >root.mainloop()
> >--------
> >And now, while the canvas has the right dimensions, the image does
> >not appear.  Okay, so "img" went from a global to local scope, but
> >that shouldn't have affected execution, right?  Have I missed something?
> >
> >This is on a Red Hat Linux system running versions 1.5.2-13 of both
> >python and tkinter.
> >
> >       - Bob Lewis
> >         bobl at tricity.wsu.edu
> 
> I was bitten by this also. You must persist the PhotoImage instance
> independently. I seem to recall that this is documented somewhere, but
> I can't remember where.
> 
> Bob

oppp, this looks like the same thing I was running with when I posted an
earlier, unrelated post. In the meantime I've figured out that making
the 'img' variable global solves the problem.... I guess this all makes
sense, but it certainly is unsettling for newbies converting stuff from
tcl/tk to python. Seems to me that their should be a better way.
Thinking aloud (I may have to try later), if one were to change the
variable containing the photoimage at a later time would the image in
the button/label change?

-- 
   __
  /  )      /         Bob van der Poel
 /--<  ____/__        bvdpoel at uniserve.com
/___/_(_) /_)         http://users.uniserve.com/~bvdpoel



More information about the Python-list mailing list