如何動態新增/移除/更新 Tkinter 視窗中的標籤?
我們可以使用 Tkinter Label 小元件來顯示文字和圖片。透過配置標籤小元件,我們可以動態更改小元件的文字、圖片和其他屬性。
為動態更新 Label 小元件,我們可以使用 config(**options) 或**內聯配置方法**,例如,為更新文字,我們可以使用 Label["text"]=text; 為移除標籤小元件,我們可以使用 pack_forget() 方法。
示例
# Import the required libraries
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
def add_label():
global label
label=Label(win, text="1. A Newly created Label", font=('Aerial 18'))
label.pack()
def remove_label():
global label
label.pack_forget()
def update_label():
global label
label["text"]="2. Yay!! I am updated"
# Create buttons for add/remove/update the label widget
add=ttk.Button(win, text="Add a new Label", command=add_label)
add.pack(anchor=W, pady=10)
remove=ttk.Button(win, text="Remove the Label", command=remove_label)
remove.pack(anchor=W, pady=10)
update=ttk.Button(win, text="Update the Label", command=update_label)
update.pack(anchor=W, pady=10)
win.mainloop()執行上述程式碼將顯示一個視窗,其中包含一些按鈕。每個按鈕都可用於在應用程式中更新/移除或新增標籤。
輸出

點選“更新標籤”按鈕後,標籤將如下更新:

廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP