如何透過程式設計方式更改 Tkinter 標籤的顏色?
Tkinter 標籤視窗小部件用於嚮應用程式新增文字或影像。我們甚至可以使用 config(options) 方法配置標籤的基本屬性。一般來說,為了動態配置視窗小部件的屬性,我們使用回撥函式,在回撥函式中修改屬性的值。
示例
在本示例中,我們將透過定義回撥函式修改 Tkinter 標籤的顏色。可以透過按鈕啟用該函式,該按鈕會強制標籤更改顏色。
#Import required libraries
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter frame
win= Tk()
#Define the geometry of the window
win.geometry("750x250")
#Define a function to Change the color of the label widget
def change_color():
label.config(bg= "gray51", fg= "white")
#Create a label
label= Label(win, text= "Hey There! How are you?", font= ('Helvetica20 italic'))
label.pack(pady=30)
#Create a Button
ttk.Button(win, text="Change Color", command=change_color).pack(pady=20)
win.mainloop()輸出
執行以上程式碼將顯示一個包含標籤和按鈕的視窗。
現在,單擊“更改顏色”按鈕來更改標籤視窗小部件的顏色。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP