Tkinter悬停在按钮上->颜色更改

Sta*_*tvs 5 python tkinter hover

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

sco*_*785 7

遗憾的是,activebackgroundand 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("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

对多个按钮执行此操作的一种简便方法是创建一个新的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()
Run Code Online (Sandbox Code Playgroud)

  • @RajMehta 问一个新问题。 (5认同)
  • 处理确实需要定义子类的多个“Button”的一种更简单的方法是让绑定函数从它们传递的事件参数中获取小部件 - 即在函数“on_enter():”中使用“e.widget.config” (background='green'))` 而不是 `myButton['background'] = 'green'`。 (2认同)

vic*_*lis 7

干净利落

上下文:基于 Unix 的计算机,可能不适用于 Windows 或 MACOSX

在您的Button对象属性中,您有标签:activebackground& activeforeground,每当与创建的实例进行交互时,这些标签就会被激活。即:您创建的按钮对象。

例如

from tkinter import *

root = Tk()

button = Button(root, text="Click me", bg="#000", fg="#fff", activebackground="#f00", activeforeground="#fff")
button.pack()

root.mainloop()
Run Code Online (Sandbox Code Playgroud)

  • 由于上面的评论以及它没有投票的事实,我几乎跳过尝试这个答案。这应该是公认的答案。它在 Linux python3 上对我来说在鼠标悬停时完美运行。 (2认同)