如何更新 Tkinter Label 小部件的图像?
我们使用 Label 小部件对应用程序中的所有小部件进行分组。Label 小部件在构造函数中获取文本和图像,该构造函数使用窗口左上角的位置设置标签。但是,若要更改或更新与 Label 关联的图像,我们可以使用一个可调用方法,在其中提供其他图像的信息。
示例
在以下示例中,我们将创建一个按钮来更新 Label 图像。
#Import the required library
from tkinter import*
from PIL import Image, ImageTk
#Create an instance of tkinter frame
win= Tk()
#Define geometry of the window
win.geometry("750x600")
win.title("Gallery")
#Define a Function to change to Image
def change_img():
img2=ImageTk.PhotoImage(Image.open("tutorialspoint.png"))
label.configure(image=img2)
label.image=img2
#Convert To PhotoImage
img1= ImageTk.PhotoImage(Image.open("logo.png"))
#Create a Label widget
label= Label(win,image= img1)
label.pack()
#Create a Button to handle the update Image event
button= Button(win, text= "Change", font= ('Helvetica 13 bold'),
command= change_img)
button.pack(pady=15)
win.bind("<Return>", change_img)
win.mainloop()输出
运行示例代码将显示一个窗口,其中包含一个 Label 图像和一个有助于更改标签图像的按钮。

现在,只需单击“更改”按钮即可更新 Label 图像。

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP