[Tutor] ImageTk problem

Michael P. Reilly arcege@shore.net
Fri, 23 Feb 2001 15:24:39 -0500 (EST)


> 
> The following code produces no error and no visible picture. The size of
> the picture is known since using a different image will change the size
> of the label. It doesn't matter whether it's a gif or a jpg.
> 
> What am I overlooking?
> 
> from Tkinter import *
> import Image, ImageTk
> 
> class Main:
>     def __init__(self,win):
>         self.win = win
>         im1 = Image.open("picture.gif")
>         im2 = ImageTk.PhotoImage(im1)
>         Label(self.win, image = im2).pack()
>         b = Button(self.win,text='Quit',height=2)
>         b.pack()
>         b.config(command = lambda w = self.win: w.destroy())
> 
> def main():
>     root = Tk()
>     Main(root)
>     root.mainloop()
> 
> if __name__ == '__main__':
>     main()

I could easily be wrong, since I don't have documentation with me,
but a reference to the image being passed of a Tkinter widget must kept
during its existance.  The easiest way to do this here would be to
assign the PhotoImage instance to "self.im2" instead of im.

Next, keep the Main instance around, otherwise again the PhotoImage
is dereferenced and the image is not displayed:

...
  self.im2 = ImageTk.PhoneImage(im1)
  Label(self.win, image=self.im2).pack()
  ...
main = Main(root)
root.mainloop()

These changes work on my FreeBSD Python 1.5 with PIL 0.3b2.

  -Arcege

-- 
------------------------------------------------------------------------
| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |
------------------------------------------------------------------------