繁体   English   中英

如何在状态激活时更改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')

它工作正常(截图):

在此输入图像描述

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

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

编辑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

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

你需要玩tkinter事件。

如果您创建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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM