Newbie question on Tkinter

Michele Simionato mis6 at pitt.edu
Wed Jul 3 13:47:37 EDT 2002


I have found a confusing (to me) behavior of Tkinter in displaying GIF
images.
Consider the following four programs (assuming you have a GIF image
called 'picture.gif' in the current directory):

#Program 1: works
import Tkinter
root=Tkinter.Tk()
img=Tkinter.PhotoImage(file='picture.gif')
lbl=Tkinter.Label(root,image=img)
lbl.pack()
Tkinter.mainloop()

#Program 2: doesn't work
import Tkinter
root=Tkinter.Tk()
lbl=Tkinter.Label(root,image=Tkinter.PhotoImage(file='picture.gif'))
lbl.pack()
Tkinter.mainloop()

#Program 3: doesn't work
import Tkinter
def DisplayPicture(root,picture):
    img=Tkinter.PhotoImage(file='picture.gif')
    lbl=Tkinter.Label(root,image=img)
    lbl.pack()
root=Tkinter.Tk()
DisplayPicture(root,'picture.gif')
Tkinter.mainloop()

#Program 4: works
import Tkinter
def DisplayPicture(root,picture):
    global img
    img=Tkinter.PhotoImage(file='picture.gif')
    lbl=Tkinter.Label(root,image=img)
    lbl.pack()
root=Tkinter.Tk()
DisplayPicture(root,'picture.gif')
Tkinter.mainloop()

The second program should give the same output of the first one,
however
the first one works, the second one gives a transparent picture! Why
??
The only difference is that there is no explicit name for the
PhotoImage object.
Moreover: program 3 has an explicit name for the PhotoImage, but the
picture is still
transparent ! Why ?? By trials, I discovered that it is possible to
fix the problem
at the price of making the PhotoImage name a global variable (see
program 4).
How can I avoid that ?
I have the same problem both with Python 1.5 and Python 2.1 on a Red
Hat Linux
7.3 machine. I also tried with Python 2.2 on Windows 98: its the same.
Therefore
I don't think this is a bug, it there should be some logic in the way
Python
display image objects via Tcl/Tk; it seems to me that there is an
issue with
the naming of objects and global/local variables. Anybody can help me
to understand ?
Is there some good reference on Tkinter ?(I have the one by Fredrik
Lundh on
http://www.pythonware.com/library/tkinter/introduction/) 

P.S. BTW, how to display jpeg images ?



More information about the Python-list mailing list