Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update the image of a Tkinter Label widget?

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?

like image 547
skeggse Avatar asked Aug 14 '10 04:08

skeggse


People also ask

Can you update labels in Tkinter?

We can use the Tkinter Label widget to display text and images. By configuring the label widget, we can dynamically change the text, images, and other properties of the widget.

Can you resize an image in Tkinter?

Build A Paint Program With TKinter and Python We can use Pillow to open the images, resize them and display in the window. To resize the image, we can use image_resize((width, height) **options) method. The resized image can later be processed and displayed through the label widget.


1 Answers

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.

like image 191
skeggse Avatar answered Sep 21 '22 01:09

skeggse