[Tutor] ImageTk problem

Harry Kattz gibbs05@flash.net
Fri, 23 Feb 2001 15:54:09 -0600


Greetings Arcege, Rick, & All,

I'm afraid I was misunderstood.  Arcege, the code I place in my last message
worked even without the modifications you suggested.  ImageLabel is not
destroyed in that version of the code.  I don't know if that code works on
your machine though.

After reading your latest post I've gone back to Rick's original code and
made the changes you suggested without adding the ImageLabel class and it
does indeed work now!  saving the reference to main was what I was missing.
The ImageLabel class isn't needed is Main is saved.

Thanks,
Sam


> >
> > 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             |                                |
> ------------------------------------------------------------------------