如何更新 Tkinter Label 小部件的图像? [英] How to update the image of a Tkinter Label widget?

查看:41
本文介绍了如何更新 Tkinter Label 小部件的图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够换出 Tkinter 标签上的图像,但我不知道该怎么做,除了更换小部件本身.

目前,我可以像这样显示图像:

导入 Tkinter 作为 tk导入 ImageTk根 = tk.Tk()img = ImageTk.PhotoImage(Image.open(path))面板 = tk.Label(根,图像 = img)panel.pack(side = "bottom", fill = "both", expand = "yes")root.mainloop()

但是,当用户点击时,说 ENTER 键,我想更改图像.

导入 Tkinter 作为 tk导入 ImageTk根 = tk.Tk()img = ImageTk.PhotoImage(Image.open(path))面板 = tk.Label(根,图像 = img)panel.pack(side = "bottom", fill = "both", expand = "yes")定义回调(e):# 改变图像root.bind("<返回>", 回调)root.mainloop()

这可能吗?

解决方案

label.configure 方法在 panel.configure(image=img) 中确实有效.

我忘记做的是包含 panel.image=img,以防止垃圾收集删除图像.

以下是新版本:

将 Tkinter 导入为 tk导入 ImageTk根 = tk.Tk()img = ImageTk.PhotoImage(Image.open(path))panel = tk.Label(root, image=img)panel.pack(side="bottom", fill="both", expand="yes")定义回调(e):img2 = ImageTk.PhotoImage(Image.open(path2))panel.configure(image=img2)panel.image = img2root.bind("<返回>", 回调)root.mainloop()

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

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?

解决方案

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.

这篇关于如何更新 Tkinter Label 小部件的图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆