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

我们使用了 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("nhooo.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()
输出结果

运行示例代码将显示一个带有标签图像的窗口和一个有助于更改标签图像的按钮。

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