[英]How to change the foreground color of ttk.Button when its state is active?
我有一個ttk.Button
,我想改變它的顏色。
我是通過以下方式完成的:
Style().configure('gray.TButton', foreground='black', background='gray')
backButton = Button(self.bottomFrame, text="Back",
command=lambda: controller.ShowFrame("StartPage"),
style='gray.TButton')
backButton.pack(side='left')
它工作正常(截圖):
但如果這個小部件處於活動模式(鼠標光標在其中),它看起來很糟糕。 背景變為白色,因此文本變得不可見。
問題 :如何在活動模式下更改文本顏色?
編輯1 :在此之后:
class BackSubmit(MainFrame):
def __init__(self, parent, controller, title):
MainFrame.__init__(self, parent, controller, title)
Style().configure('gray.TButton', foreground='white', background='gray')
backButton = Button(self.bottomFrame, text="Back",
command=lambda: controller.ShowFrame("StartPage"),
style='gray.TButton')
backButton.bind( '<Enter>', self.UpdateFgInAcSt )
backButton.pack(side='left')
Style().configure('blue.TButton', foreground='blue', background='light blue')
submitButton = Button(self.bottomFrame,
text="Submit settings",
command=lambda: self.submitSettings(),
style='blue.TButton')
submitButton.pack(side=RIGHT)
def submitSettings(self):
raise NotImplementedError("Subframe must implement abstract method")
def UpdateFgInAcSt(self, event):
backButton.configure(activeforeground='gray')
我收到錯誤:
backButton.configure(activeforeground='gray') NameError: global name 'backButton' is not defined
。
你需要玩tkinter事件。
如果您創建2個相應的函數,則Enter
和Leave
事件將完全滿足您的目標:
def update_bgcolor_when_mouse_enters_button(event):
backButton.configure(background='black') # or whatever color you want
def update_bgcolor_when_mouse_leaves_button(event):
backButton.configure(background='gray')
然后將這兩個函數綁定到您的按鈕:
backButton.bind('<Enter>', update_bgcolor_when_mouse_enters_button)
backButton.bind('<Leave>', update_bgcolor_when_mouse_leaves_button)
您可以使用文本的顏色而不是按鈕的背景顏色,而是使用foreground
選項。
更便宜的方法包括僅使用Enter
事件並在activeforground
選項上播放。
在這里,您只需要定義一個函數:
def update_active_foreground_color_when_mouse_enters_button(event):
backButton.configure(activeforeground='gray')
然后將此函數綁定到Enter
事件,如下所示:
backButton.bind('<Enter>', update_active_foreground_color_when_mouse_enters_button)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.