[Tutor] ImageTk problem

Michael P. Reilly arcege@shore.net
Fri, 23 Feb 2001 16:29:22 -0500 (EST)


> 
> Greetings Rick & All,
> 
> I've been having the same kind problems with PIL.
> 
> I think Michael Reilly is correct about retaining a reference, though I
> couldn't get his solution to work under Windows.
> 
> I could get Rick's example to work when I modified it as follows to match
> examples by creating a subclass of Label to hold the image:
> 
> from Tkinter import *
> import Image, ImageTk
> 
> class ImageLabel(Label):
> 
>     def __init__(self, master, im):
> 
>         self.im2 = ImageTk.PhotoImage(im)
>         Label.__init__(self, master, image=self.im2)
> 
> class Main:
>     def __init__(self,win):
>         self.win = win
>         im1 = Image.open("picture.gif")
>         ImageLabel(self.win, im = im1).pack()
          # keep a reference beyond the end of the method
          self.iml = ImageLabel(self.win, im=im1).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)
      # keep a reference until at least after mainloop()
      main = Main(root)

>     root.mainloop()
> 
> if __name__ == '__main__':
>     main()
> 
> 
> I really don't know why this works and the other doesn't.

For the same reason I said to keep a reference to Main(root) as well,
you lose the reference to ImageLabel (it gets created, packed then
dereferenced inside of Main.__init__), and still lose the reference
to Main(root) inside of main().

The interaction between Tk and Tkinter is a little odd where it
comes to sharing objects.  One place this is clear is the "Variable"
classes (StringVar, Intvar, etc.).  Suffice to say, if the Python
version of the PhotoImage or BitmapImage (in Tkinter or PIL) is
destroyed, then Tcl/Tk will remove its reference as well.

  -Arcege

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