[Tutor] Images + Tkinter

Gregor Lingl glingl@aon.at
Sun Nov 17 07:06:00 2002


Martin v. Loewis has sent me the following explanation:

Gregor Lingl <glingl@aon.at> writes:

>> Does anybody know the secrets, which lie behind this mystery?
>  
>

When you drop the last reference to an Tkinter.Image object, the image
is destroyed. So always keep a reference to an image that you want to use.

Regards,
Martin

This means, for instance, that inserting a global statement solves
the problem:

import Tkinter
from Tkconstants import *

def window(tk):
    global photo       #### SIC!
    frame=Tkinter.Frame(tk)
    frame.pack()
    canvas=Tkinter.Canvas(frame,width=400,height=500)
    canvas.pack()
    photo=Tkinter.PhotoImage(file="picture.gif")
    canvas.create_rectangle(10,20,30,40, fill="red")
    canvas.create_image(200, 250, image=photo)
    button=Tkinter.Button(frame, text="EXIT", command=tk.destroy)
    button.pack()

root = Tkinter.Tk()
window(root)
root.mainloop()