如何更新Tkinter Label小部件的图像?

ske*_*gse 33 python tkinter python-imaging-library python-2.7

我希望能够在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()
Run Code Online (Sandbox Code Playgroud)

但是,当用户点击时,比如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()
Run Code Online (Sandbox Code Playgroud)

这可能吗?

ske*_*gse 50

该方法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()
Run Code Online (Sandbox Code Playgroud)

原始代码有效,因为图像存储在全局变量中img.

  • 是的,但让我看起来好像已经想出了一个解决方案对我来说是不公平的,因为我并不是真正想出解决方案的人。 (3认同)

小智 8

另一种选择来做到这一点。

使用面向对象的编程并带有交互式界面来更新图像。

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()
Run Code Online (Sandbox Code Playgroud)

将“cualitiva.jpg”替换为您要使用的默认图像。