【问题标题】:Tkinter Hovering over Button -> Color changeTkinter 悬停在按钮上-> 颜色变化
【发布时间】:2018-09-28 00:59:45
【问题描述】:

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

【问题讨论】:

  • 悬停在其上之后或同时悬停在其上?你用的是ttk吗?请向我们展示您的代码的minimal reproducible example
  • Buttons 有一些选项,您可以在构建一个当光标在它们上方时控制其颜色的选项时传递它们,称为 activebackgroundactiveforeground,尝试设置和使用这些选项。这是一些documentation

标签: python tkinter hover


【解决方案1】:

遗憾的是,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()

正如 cmets 中所指出的,如果我们想要多个按钮,我们可以将按钮绑定到使用 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()

【讨论】:

  • 如果我想在鼠标悬停时更改按钮中的图像怎么办?
  • @RajMehta 问一个新问题。
  • 处理多个需要定义子类的Buttons 的更简单方法是让绑定函数从它们传递的事件参数中获取小部件——即在函数on_enter(): 中使用@ 987654331@ 而不是 myButton['background'] = 'green'
  • @martineau 我已经更新了答案以包含此选项。
  • scotty3785:是的,这就是使回调可重用的方法,正如我所建议的那样——所以现在你的答案更加全面。 ;¬)
【解决方案2】:

简单明了

在您的Button 对象属性中,您有标签:activebackgroundactiveforeground,只要与创建的实例交互就会激活。也就是:你创建的按钮对象。

例如

from tkinter import *

root = Tk()

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

root.mainloop()

【讨论】:

  • 由于上面的 cmets 以及它没有投票的事实,我几乎跳过了尝试这个答案。这应该是公认的答案。它对我在 Linux python3 上的鼠标悬停非常有效。
  • 必须注意的一点是,存在 Button 和 ttk.Button 对象。查看 ttk.Button 对象的解决方案 -> stackoverflow.com/questions/27347981/…
  • 我认为它的支持率较低,因为它似乎不适用于在分布有许多 GUI 应用程序的 Windows 10 中悬停。
猜你喜欢
  • 2016-05-18
  • 2020-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-30
  • 2016-07-20
  • 2016-05-26
相关资源
最近更新 更多