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

輸出

執行上面的程式碼,將顯示包含影像的標籤的視窗。當我們單擊“更新”按鈕時,標籤影像將得到更新。

現在,單擊“更新”按鈕來更新標籤小部件及其物件。

更新於: 22-07-2021

3K+ 瀏覽次數

開啟你的 事業

透過完成課程獲得認證

開始學習
廣告