在类中向我的按钮添加悬停选项

2024-04-25 14:12:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为我已经实现的多个按钮添加一个悬停选项,但我想在一个类中这样做,以节省我单独为每个按钮添加选项。 我用python编写代码,并使用tkinter作为GUI。在

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)

不知道如何绑定鼠标悬停选项一次,它适用于我的所有按钮。在

任何帮助将不胜感激!在


Tags: textself选项columnbuttonwindow按钮command
1条回答
网友
1楼 · 发布于 2024-04-25 14:12:45

Instance and Class Bindings

But Tkinter also allows you to create bindings on the class and application level; in fact, you can create bindings on four different levels:

  • the widget class, using bind_class (this is used by Tkinter to provide standard bindings)

还有例子

By the way, if you really want to change the behavior of all text widgets in your application, here’s how to use the bind_class method:

top.bind_class("Text", "", lambda e: None)

所以使用bind_class和{}和{}可以做到。在

编辑:示例-当鼠标enter/hover任何按钮时,都将调用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()

您还可以创建自己的小部件来更改现有的小部件。在

红色按钮:

^{pr2}$

或者

class RedButton(Button):

    def __init__(self, parent, **options):
        Button.__init__(self, parent, bg='red', **options)

编辑:

如果你只需要改变悬停按钮的颜色,那么你就不需要绑定函数了。按钮有activebackground=activeforeground=。在

import tkinter as tk

root = tk.Tk()

btn = tk.Button(root, text="HOVER", activebackground='blue', activeforeground='red')
btn.pack()

root.mainloop()

Button

编辑:它在Windows、Linux和OS X上的行为可能不同

相关问题 更多 >