将悬停在Button上后,是否可以更改其背景颜色? Tkinter中的代码是什么?

最佳答案

遗憾的是,activebackgroundactiveforeground选项似乎仅在单击按钮时才起作用,而不是在将鼠标悬停在按钮上时起作用。改用<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("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)

root.mainloop()
如评论中所指出的,如果我们需要多个按钮,则可以将按钮绑定(bind)到使用click事件的事件数据来更改按钮背景的函数。
import tkinter as tk

def on_enter(e):
    e.widget['background'] = 'green'

def on_leave(e):
    e.widget['background'] = 'SystemButtonFace'

root = tk.Tk()
myButton = tk.Button(root,text="Click Me")
myButton.grid()


myButton.bind("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)

myButton2 = tk.Button(root,text="Click Me")
myButton2.grid()


myButton2.bind("<Enter>", on_enter)
myButton2.bind("<Leave>", 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("<Enter>", self.on_enter)
        self.bind("<Leave>", 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()

关于python - Tkinter悬停在按钮上->颜色更改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49888623/

10-11 20:04
查看更多