当鼠标悬停在Tkinter中的一个Button
上时,是否有可能更改其背景色?如果可以,该使用什么代码实现?
遗憾的是,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("<Enter>", on_enter)
myButton.bind("<Leave>", on_leave)
root.mainloop()
正如评论中指出的那样,如果我们想要多个按钮,我们可以将按钮绑定到使用点击事件的事件数据来更改按钮背景的函数。
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
的一种更简单的方法是,让绑定的函数从它们传递的事件参数中获取小部件,而不需要定义子类。例如,在函数on_enter()
中使用e.widget.config(background='green')
,而不是myButton['background'] = 'green'
。 - martineau;¬)
- martineauon_enter
和on_leave
函数,通过在方法内部更改图像的代码来实现。 - SamTheProgrammer简单明了
背景:针对基于Unix的计算机,可能不适用于Windows或MACOSX
在您的按钮
对象属性中,您有标签: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()
Button
时,您可以传递一些选项来控制鼠标悬停时的颜色,这些选项称为activebackground
和activeforeground
,尝试设置并使用它们。这里有一些文档。 - martineau