Python 向类中的“我的按钮”添加悬停选项
我试图为我已经实现的多个按钮添加一个悬停选项,但是我想在一个类中这样做,以保存我将选项单独添加到每个按钮的操作。 我正在用python编写代码,并在GUI中使用tkinterPython 向类中的“我的按钮”添加悬停选项,python,tkinter,Python,Tkinter,我试图为我已经实现的多个按钮添加一个悬停选项,但是我想在一个类中这样做,以保存我将选项单独添加到每个按钮的操作。 我正在用python编写代码,并在GUI中使用tkinter class GUIButtons(): def __init__(self, window): self.window = window self.Calculate = Button(window, command=GetUnits, text="Calculate", wi
class GUIButtons():
def __init__(self, window):
self.window = window
self.Calculate = Button(window, command=GetUnits, text="Calculate", width = 19, background = "dark blue", fg="white")
self.Calculate.grid(row=1, column=4, sticky=NSEW)
self.ShowMethod = Button(window, command=ShowMethod, text="Show method", width = 19, background = "darkblue", fg="white")
self.ShowMethod.grid(row=1, column= 5, sticky=NSEW)
self.Submit = Button(window, command = lambda: GetCoordinate(Message), text="Submit", width = 6, height = 1, background = "dark blue", fg="white", font = 11)
self.Submit.grid(row=3, column = 3, sticky = NSEW)
self.Displacement = Button(window, text="Displacement", background = "Dark Blue", fg="white", font=11)
self.Displacement.grid(row=2, column=1, sticky= N)
不知道如何绑定一次鼠标悬停选项,使其应用于我的所有按钮
任何帮助都将不胜感激 见
但是Tkinter还允许您在类和
应用水平;事实上,您可以在四个不同的服务器上创建绑定
级别:
- 小部件类,使用绑定类(Tkinter使用它来提供 标准绑定)
bind\u class
与
和
可以做到这一点
--
编辑:示例-当鼠标进入/悬停
任何按钮时,将调用test()
from tkinter import *
# ---
def test(event):
print(event)
# ---
window = Tk()
# created befor binding
Button(window, text="Button #1").pack()
Button(window, text="Button #2").pack()
Button(window, text="Button #3").pack()
window.bind_class('Button', '<Enter>', test)
# created after binding
Button(window, text="Button #4").pack()
window.mainloop()
或
--
编辑:
若你们只需要改变悬停按钮的颜色,那个么你们不需要绑定函数。按钮具有activebackground=
和activeforeground=
import tkinter as tk
root = tk.Tk()
btn = tk.Button(root, text="HOVER", activebackground='blue', activeforeground='red')
btn.pack()
root.mainloop()
看
编辑:它在Windows、Linux和OS X上的行为可能不同您好,感谢您花时间帮助我编写代码。我有点搞不懂你的建议。我想为我所有的按钮创建一个悬停特性,而不单独对每个按钮进行悬停,因此这个类。我是python新手,所以如果这些都没有意义,我很抱歉。您可以使用
bind_类('Button','',function_name)
将
事件绑定到所有按钮
,当鼠标进入/悬停
按钮时,它将调用function_name
。或者当您说“悬停功能”时,您可能会想到一些不同的事情大家好,再次感谢这些例子,它们非常有帮助。我现在已经有了所有的按钮定制与该类。但是,我仍然在努力使用悬停功能。当鼠标悬停在按钮上时,我希望我的按钮也能改变颜色,但当我尝试.bind()时,我会收到一条错误消息,说“object has no attribute bind”,将代码添加到pastebin.org并放置链接。如果只需要更改悬停颜色,请使用activeforeground=
和activebackground=
class RedButton(Button):
def __init__(self, parent, **options):
Button.__init__(self, parent, bg='red', **options)
import tkinter as tk
root = tk.Tk()
btn = tk.Button(root, text="HOVER", activebackground='blue', activeforeground='red')
btn.pack()
root.mainloop()