[英]Tkinter Hovering over Button -> Color change
悬停在Button
上后是否有可能更改按钮的背景颜色? Tkinter 中的代码是什么?
遗憾的是, 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 类,该类修改默认按钮的行为,以便在悬停时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()
在您的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()
它在 Linux python3 上对我来说在鼠标悬停时完美运行。
<\/blockquote>不幸的是,它在 Windows 10 上根本不起作用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.