我有一个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')
Run Code Online (Sandbox Code Playgroud)
而且效果很好(截图):
但如果这个小部件处于活动模式(鼠标光标在其中),它看起来很糟糕。背景变成白色,因此文本变得不可见。
问题:如何在活动模式下更改文本颜色?
编辑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')
Run Code Online (Sandbox Code Playgroud)
我收到错误:
backButton.configure(activeforeground='gray')
NameError: global name 'backButton' is not defined。
您需要使用tkinter 事件。
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')
Run Code Online (Sandbox Code Playgroud)
然后将这两个函数绑定到您的按钮:
backButton.bind('<Enter>', update_bgcolor_when_mouse_enters_button)
backButton.bind('<Leave>', update_bgcolor_when_mouse_leaves_button)
Run Code Online (Sandbox Code Playgroud)
您可以使用文本颜色而不是按钮的背景颜色执行相同的操作,但使用该foreground选项。
一种更便宜的方法是仅使用Enter事件并根据activeforground选项进行游戏。
这里只需要定义一个函数:
def update_active_foreground_color_when_mouse_enters_button(event):
backButton.configure(activeforeground='gray')
Run Code Online (Sandbox Code Playgroud)
然后将此函数绑定到Enter事件,如下所示:
backButton.bind('<Enter>', update_active_foreground_color_when_mouse_enters_button)
Run Code Online (Sandbox Code Playgroud)