如何在状态激活时更改ttk.Button的前景色?

时间:2017-06-02 07:48:16

标签: python colors ttk

我想要改变一种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')

它工作正常(截图):

enter image description here

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

问题:如何在活动模式下更改文字颜色?

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

1 个答案:

答案 0 :(得分:3)

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

您需要使用tkinter events.

如果您创建2个相应的函数,

EnterLeave事件将完全满足您的目标:

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)
相关问题