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?
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With