如何更新Tkinter标签窗口小部件的图像? [英] How to update the image of a Tkinter Label widget?
本文介绍了如何更新Tkinter标签窗口小部件的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够交换出Tkinter标签上的图像,但是除了替换小部件本身之外,我不确定该怎么做.
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()
但是,当用户点击时,说出ENTER
键,我想更改图像.
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()
这可能吗?
推荐答案
方法label.configure
在panel.configure(image=img)
中有效.
我忘记做的是包含panel.image=img
,以防止垃圾回收删除图像.
What I forgot to do was include the panel.image=img
, to prevent garbage collection from deleting 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):
img2 = ImageTk.PhotoImage(Image.open(path2))
panel.configure(image=img2)
panel.image = img2
root.bind("<Return>", callback)
root.mainloop()
原始代码有效,因为图像存储在全局变量img
中.
The original code works because the image is stored in the global variable img
.
这篇关于如何更新Tkinter标签窗口小部件的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文