如何更新 Python/tkinter 标签小部件?
Tkinter 提供了操作文本和图像相关对象的内置功能。标签小部件用文本和图像注释用户界面。我们可以向标签小部件提供任何文本或图像,使其显示在应用程序窗口中。
假设对于某个特定的应用程序,我们需要更新标签小部件。标签小部件是一个容器,可以包含文本或图像。在以下示例中,我们将通过配置一个按钮来更新标签图像。
示例
#Import the required library from tkinter import * from PIL import Image,ImageTk from tkinter import ttk #Create an instance of tkinter frame win= Tk() #Define geometry of the window win.geometry("750x450") #Define a Function to update to Image def update_img(): img2=ImageTk.PhotoImage(Image.open("logo.png")) label.configure(image=img2) label.image=img2 #Load the Image img1= ImageTk.PhotoImage(Image.open("logo1.png")) #Create a Label widget label= Label(win,image= img1) label.pack() #Create a Button to handle the update Image event button= ttk.Button(win, text= "Update", command= update_img) button.pack(pady=15) win.bind("<Return>", update_img) win.mainloop()
输出
运行上面的代码,将显示包含图像的标签的窗口。当我们单击“更新”按钮时,标签图像将得到更新。
现在,单击“更新”按钮来更新标签小部件及其对象。
广告