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

时间:2010-08-14 04:59:32

标签: python python-2.7 tkinter python-imaging-library

我希望能够在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()

这可能吗?

3 个答案:

答案 0 :(得分:42)

方法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中。

答案 1 :(得分:0)

另一种选择。

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

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()

替换&#39; cualitativa.jpg&#39;对于您要使用的默认图像。

答案 2 :(得分:0)

另一种可能有帮助的解决方案。

就我而言,我有两个 tk.Tk() 窗口。使用 ImageTk.PhotoImage() 时,对象默认将其 tk 窗口设置为第一个创建的窗口。对此的一个简单解决方法是传递您想要的 tk 窗口 ImageTk.PhotoImage(img, master=your_window)

import tkinter as tk 
from PIL import ImageTk, Image
if __name__ == '__main__':
     main_window = tk.Tk()
     second_window = tk.Tk()
     
     main_canvas = Canvas(second_window)
     main_canvas.pack()
     
     filename = 'test.png'

     img = Image.open(filename)
     img = img.resize((300, 100), Image.ANTIALIAS)
     logo = ImageTk.PhotoImage(img, master=second_window)
     logo_label = Label(master=main_canvas, image=logo)
     logo_label.image = logo
     logo_label.pack()

     main_window.mainloop()
相关问题