遗憾的是,activebackground和activeforeground选项仅在单击按钮时才起作用,而不是将鼠标悬停在按钮上时才起作用.使用< Leave>和< Enter>事件代替
import tkinter as tk
def on_enter(e):
myButton['background'] = 'green'
def on_leave(e):
myButton['background'] = 'SystemButtonFace'
root = tk.Tk()
myButton = tk.Button(root,text="Click Me")
myButton.grid()
myButton.bind("", on_enter)
myButton.bind("", on_leave)
root.mainloop()
对多个按钮执行此操作的一种更轻松的方法是创建一个新的Button类,该类修改默认按钮的行为,以便当您将鼠标悬停时activebackground实际上可以工作.
import tkinter as tk
class HoverButton(tk.Button):
def __init__(self, master, **kw):
tk.Button.__init__(self,master=master,**kw)
self.defaultBackground = self["background"]
self.bind("", self.on_enter)
self.bind("", self.on_leave)
def on_enter(self, e):
self['background'] = self['activebackground']
def on_leave(self, e):
self['background'] = self.defaultBackground
root = tk.Tk()
classButton = HoverButton(root,text="Classy Button", activebackground='green')
classButton.grid()
root.mainloop()