Tkinter displaying an image in a button
Richard Chamberlain
richardSPAM at geotek.co.uk
Thu Nov 22 07:30:30 EST 2001
I believe he's using pil to support jpg.
This garbage collection problem has been around for quite a while, it's just
clearing up local variables and taking your image with it.
You could also make img and phi an attribute of the class as in:
from Tkinter import *
import Image, ImageTk
class App:
def __init__(self, master):
self.img = Image.open('c:/water.jpg')
self.phi = ImageTk.PhotoImage(self.img)
button = Button( master, image=self.phi )
button.pack()
root = Tk()
app = App(root)
root.mainloop()
Richard
"Sébastien Cabot" <sebascabot at sympatico.ca> wrote in message
news:%Y2L7.14855$QC5.2230883 at news20.bellglobal.com...
> 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