Trouble displaying image with tkinter

jmdeschamps at gmail.com jmdeschamps at gmail.com
Sun Aug 6 18:52:02 EDT 2006


sj wrote:
> I am just learning to use Tkinter and am having problems displaying image
> files. I am able to display an image using tutorials (such as
> http://www.daniweb.com/code/snippet296.html) But when I try my own code all
> I get is an empty widget. What is wrong with the following program?
>
>
>
> from Tkinter import *
>
> class Foo(Frame):
>
>     def __init__(self,master=None):
>         Frame.__init__(self,master)
>         self.pack()
>         self.createWidgets()
>
>
>     def createWidgets(self):
>
>         self.qbutton = Button(self)
>         self.qbutton["text"] = "Quit"
>         self.qbutton["command"] = self.quit
>         self.qbutton.pack(side = "top")
>
>         idata =
> PhotoImage(file="/home/sj/documents/projects/xaed/images/cat_001.gif")
>
>         canvas = Canvas(width=300,height=200)
>         canvas.pack(side="top",fill=BOTH,expand=YES)
>         canvas.create_image(50,10,image=idata,anchor=NW)
>
>         ## lab = Label(self,image=idata)
>         ## lab.pack(side=TOP)
>
>
> root = Tk()
> app = Foo(root)
> app.mainloop()
> #app.destroy()

If you keep a reference of the photoImage object then it will work!
...
self.idata=
PhotoImage(file="/home/sj/documents/projects/xaed/images/cat_001.gif")
...
canvas.create_image(50,10,image=iself.data,anchor=NW)
...
By making the PhotoImage an attribute of your object, you keep a
reference that the garbage collector will NOT collect, So you're image
will continue to exist and thus be rendered by the canvas.

JM




More information about the Python-list mailing list