在 Python 中為 Tkinter 設定背景顏色


我們可以使用 tkinter.ttk 模組自定義 tkinter 小部件。Tkinter.ttk 模組用於設定 tkinter 小部件的樣式,例如設定背景色、前景色、啟用按鈕、向標籤新增影像、調整小部件的高度和寬度等。

為了在 tkinter 小部件中新增背景色,我們可以在小部件中指定background 屬性。

示例

在以下示例中,我們將建立一個按鈕,該按鈕將更改文字標籤的背景。

#Import the tkinter library
from tkinter import *
from tkinter.ttk import *

#Create an instance of tkinter frame
win = Tk()

#Set the geometry
win.geometry("600x400")

#Add a class to style the tkinter widgets

style = ttk.Style()
style.configure('TEntry', foreground = 'red')

#Define a function to change the text color
def change_color():
   text.configure(background="red")

#Create a text widget
text=Label(win,text="This is a New Text",foreground="black",
background="yellow",font=('Aerial bold',20))
text.pack(pady=20)

#Create a Button widget
Button(win, text= "Click Here", command= change_color).pack(pady=10)
win.mainloop()

輸出

執行以上程式碼將建立一個視窗,其中包含一個文字標籤,背景顏色為“黃色”。

現在,單擊“單擊此處”按鈕。它將文字標籤的背景顏色更改為“紅色”。

更新於: 2021-03-26

2 千多次瀏覽

職業 起航

完成課程獲認證

開始操作
廣告