Newbie: question about Tkinter

Howard Lightstone howard at eegsoftware.com
Fri Feb 28 12:59:42 EST 2003


built4living at excite.com (Locash) wrote in 
news:d8a7d55e.0302280933.66a65ed3 at posting.google.com:

> Hi,
> 
> I am a recreational programmer who has decided to give Python a try. 
> Up until this point, I have always managed to find a resource that
> would help me out when I got into trouble, but not this time.  I
> recently turned my attention towards tkinter, and I am afraid I am
> stumped.  I just want to know how to put an image on a canvas.  I am
> sure I am missing something simple, but can someone help me out?  TIA.
> 
> This is what I have:
> 
> ~~~~~~~~~~~~~~~~~~~~~~~~~~
> 
> from Tkinter import *
> 
> class Application(Frame):
>         
>     def __init__(self, master=None):
>         
>         Frame.__init__(self, master)
>         self.pack()
>         self.createWidgets()
>         
>     def createWidgets(self):
>         
>         img = PhotoImage(file='test.gif')
>         
>         self.canvas = Canvas(self, height=200, width=300, bg='white')
>         self.canvas.pack()               
>         self.canvas.create_image (10, 10, image=img)
>     
> app = Application() 
> 
> app.mainloop()
> 
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> 
> When I run this, I get the frame and the canvas, but nothing on it. 
> What am I missing?
> 
> Thanks,
> Locash
> 

The problem is that "img" does not have a reference once you leave 
createWidgets and so goes away.

The easy answer is to just add a reference to your canvas object:
after the line
 
         self.canvas.pack()
   
add the line

         self.canvas.img = img            




More information about the Python-list mailing list