如何更新 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