如何更新Tkinter标签小部件的图像?
问题描述:
我希望能够换出Tkinter标签上的图像,但我不知道如何去做,除了替换小部件本身。如何更新Tkinter标签小部件的图像?
目前,我可以像这样显示图像:
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
关键,我想改变形象。
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
,以防止垃圾收集删除图像。
以下是新版本:
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
。
答
另一种选择。
使用面向对象的编程和交互式界面来更新图像。
from Tkinter import *
import tkFileDialog
from tkFileDialog import askdirectory
from PIL import Image
class GUI(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
w,h = 650, 650
master.minsize(width=w, height=h)
master.maxsize(width=w, height=h)
self.pack()
self.file = Button(self, text='Browse', command=self.choose)
self.choose = Label(self, text="Choose file").pack()
self.image = PhotoImage(file='cualitativa.gif')
self.label = Label(image=self.image)
self.file.pack()
self.label.pack()
def choose(self):
ifile = tkFileDialog.askopenfile(parent=self,mode='rb',title='Choose a file')
path = ifile.name
self.image2 = PhotoImage(file=path)
self.label.configure(image=self.image2)
self.label.image=self.image2
root = Tk()
app = GUI(master=root)
app.mainloop()
root.destroy()
将'cualitativa.jpg'替换为您要使用的默认图像。
回调中的行是否应该读取'panel.image = img2'? – 101 2015-02-27 03:25:59
@ figs看起来很有道理。我不记得具体修改这个用法,但这也是四年前。你可以测试它来验证吗? – skeggse 2015-03-16 03:11:28
是的,这可能是问题所在。测试的代码略有不同,但具有相同的问题。 – 2015-03-26 14:56:44