Tkinter displaying an image in a button

Sébastien Cabot sebascabot at sympatico.ca
Thu Nov 22 12:49:55 CET 2001


First in Tkinter.py we have:

  class PhotoImage(Image):
      """Widget which can display colored images in GIF, PPM/PGM format."""

This mean for me no ".jpg".

Now for the problem:

Look's like the PhotoImage object got a sys.getrefcount(img) == 0 and is
garbage collected right away, even if the Button object still need this
object.

So this work:

  from Tkinter import *
  root = Tk()
  i = PhotoImage(file="but1.gif")
  Button(root, image=i).pack()
  root.mainloop()

And this don't work:

  from Tkinter import *
  root = Tk()
  Button(root, image=PhotoImage(file="but.gif")).pack()
  root.mainloop()

No doubt, this is a refcount bug in Tkinter.

Now a quick patch to get around this bug is to keep your PhotoImage allocate
for all the duration of your application.
Be carefull, PhotoImage must be call only after the Tk() call.

So a solution could be:

  from Tkinter import *

  class App:
    def __init__(self, parent):
      global BUT1
      Button(parent, image=BUT1).pack()

  root = Tk()
  BUT1 = PhotoImage(file="but1.gif")
  App(root)
  root.mainloop()

Hope this will help.

(Note: I tested this with Python 2.1.1 on Debian)

Good Luck!
Bye.

"David R. Smith" <drs at alex2.labs.agilent.com> wrote in message
news:3BFC3295.20FC3F02 at alex2.labs.agilent.com...
> The first code snippet below successfully displays an image, whereas the
> second just shows gray where the image should be.  What's wrong with the
> class version, and what do I have to do to get it to work?
> (I am using Python 2.0.1 on Debian.)
>
>     adTHANKSvance
>     David Smith
>
>
>
> from Tkinter import *
> import Image, ImageTk
> root = Tk()
> img = Image.open('SonicCruiser.jpg')
> phi = ImageTk.PhotoImage(img)
> button = Button(root, image=phi)
> button.pack()
> root.mainloop()
>
>
>
> from Tkinter import *
> import Image, ImageTk
> class App:
>     def __init__(self, master):
>         img = Image.open('SonicCruiser.jpg')
>         phi = ImageTk.PhotoImage(img)
>         button = Button( master, image=phi )
>         button.pack()
> root = Tk()
> app = App(root)
> root.mainloop()





More information about the Python-list mailing list