如何在 ttk.Button 处于活动状态时更改它的前景色?

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')

它工作正常(截图):

但是如果这个小部件处于活动模式(鼠标光标在其中),它看起来很糟糕。背景变为白色,因此文本变得不可见。

问题:如何在active模式下更改文本颜色?

EDIT1:在此之后:

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.

第一种方法:2 个函数绑定到 2 个不同的事件

你需要玩玩 tkinter events.

EnterLeave 事件将完全满足您的目标,如果您创建 2 个相应的功能如下:

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 选项。

更便宜的方法:1 个函数绑定到 1 个事件

一种更便宜的方法是仅使用 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)