views:

111

answers:

1

My question is similar to here, 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 and 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?

+1  A: 

As Alex Martelli stated in his [now deleted] answer, the method label.configure does works in panel.configure(image = img). What I forgot to do was include the panel.image = img, to prevent garbage collection from deleting the image. Therefore:

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 = img
root.bind("<Return>", callback)
root.mainloop()

The reason the original code works, is that the image is stored in the global variable img.

CMC