How to update the image of a Tkinter Label widget?

skeggse picture skeggse · Aug 14, 2010 · Viewed 74.8k times · Source

I would like to be able to swap out an image on a Tkinter label, but I'm not sure how to do it, except for replacing the widget itself.

Currently, I can display an image like so:

import Tkinter as tk
import ImageTk

root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
root.mainloop()

However, when the user hits, say the ENTER key, I'd like to change the image.

import Tkinter as tk
import ImageTk

root = tk.Tk()

img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")

def callback(e):
    # change image

root.bind("<Return>", callback)
root.mainloop()

Is this possible?

Answer

skeggse picture skeggse · Aug 14, 2010

The method label.configure does work in panel.configure(image=img).

What I forgot to do was include the panel.image=img, to prevent garbage collection from deleting the image.

The following is the new version:

import Tkinter as tk
import ImageTk


root = tk.Tk()

img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")

def callback(e):
    img2 = ImageTk.PhotoImage(Image.open(path2))
    panel.configure(image=img2)
    panel.image = img2

root.bind("<Return>", callback)
root.mainloop()

The original code works because the image is stored in the global variable img.