How to update the image of a Tkinter Label widget?

Viewed 104743

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?

3 Answers

Another solution that might be of help.

In my case, I had two tk.Tk() windows. When using ImageTk.PhotoImage(), the object defaults to setting its tk window to being the first one created. A simple fix to this is to pass the tk window that you want as such ImageTk.PhotoImage(img, master=your_window)

import tkinter as tk 
from PIL import ImageTk, Image
if __name__ == '__main__':
     main_window = tk.Tk()
     second_window = tk.Tk()
     
     main_canvas = Canvas(second_window)
     main_canvas.pack()
     
     filename = 'test.png'

     img = Image.open(filename)
     img = img.resize((300, 100), Image.ANTIALIAS)
     logo = ImageTk.PhotoImage(img, master=second_window)
     logo_label = Label(master=main_canvas, image=logo)
     logo_label.image = logo
     logo_label.pack()

     main_window.mainloop()
Related