如何在 Tkinter 中更改 ttk 按鈕顏色?


Tkinter 元件在所有平臺和作業系統中都具有統一的外觀和樣式。Ttk 在 HTML 指令碼中相當於 CSS。它具有許多可為常規 tkinter 元件新增樣式的內建函式、模組和方法。Tkinter ttk 按鈕通常具有預設顏色方案,因此我們可以透過配置方法更改這些按鈕的背景顏色。

示例

在此示例中,我們將建立一個按鈕,按此按鈕會更改其樣式。

#Import the necessary library
import itertools
from tkinter import *
from tkinter import ttk
#Create an instance of tkinter window
win = Tk()
#Set the geometry of tkinter window
win.geometry("750x250")
#Define the style
style_1 = {'fg': 'black', 'bg': 'RoyalBlue3', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_2 = {'fg': 'white', 'bg': 'OliveDrab2', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_3 = {'fg': 'black', 'bg': 'purple1', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_4 = {'fg': 'white', 'bg': 'coral2', 'activebackground':
'gray71', 'activeforeground': 'gray71'}
style_cycle = itertools.cycle([style_1, style_2, style_3, style_4 ])
#Define a function to update the button style
def update_style():
style = next(style_cycle)
button.configure(**style)
#Create a tk button
button = Button(win,width=40,font=('Helvetica 18 bold'), text="Change
Style", command=update_style)
button.pack(padx=50, pady=50)
win.mainloop()

輸出

執行上述程式碼會顯示一個帶按鈕的視窗。單擊按鈕時,它將切換背景色和文字顏色樣式。

現在,單擊按鈕更改按鈕顏色。

更新日期: 2021-04-15

5 千+ 瀏覽

開啟你的職業

透過完成課程獲得認證

開始使用
廣告