【问题标题】:How can I pass the TKinter button/label that triggered a bind to a function which that bind calls?如何将触发绑定的 TKinter 按钮/标签传递给绑定调用的函数?
【发布时间】:2021-09-24 17:53:38
【问题描述】:

我希望有人可以帮助解决这个问题。我是编码新手,想尝试用 TKinter 在 Python 中做一些 GUI 的东西。在我的一个项目中,我希望鼠标悬停在任何按钮上以更改其背景颜色。但是我不想为每个按钮定义一个函数。这是一个例子:

from tkinter import *

root = Tk()
root.title("Example")
root.configure(bg="black")

def on_enter(e, button):
    #button = Button that triggered the bind
    button.configure(bg="red")

def on_leave(e, button):
    #button = Button that triggered the bind
    button.configure(bg="black")

button1 = Button(root, text="Button1", width=10, height=10, bg="black", fg="white")
button2 = Button(root, text="Button2", width=10, height=10, bg="black", fg="white")
button3 = Button(root, text="Button3", width=10, height=10, bg="black", fg="white")
button4 = Button(root, text="Button4", width=10, height=10, bg="black", fg="white")

button1.grid(column=0, row=0)
button2.grid(column=0, row=1)
button3.grid(column=1, row=0)
button4.grid(column=1, row=1)

#How can I give the button that triggered the bind as an argument to the functions on_enter/on_leave?
root.bind_all("<Enter>", lambda e, button: on_enter(e, button))
root.bind_all("<Leave>", lambda e, button: on_leave(e, button))

#root.bind_class("Button", "<Enter>", lambda e, button: on_enter(e, button))
#root.bind_class("Button", "<Leave>", lambda e, button: on_leave(e, button))


root.mainloop()

现在我当然可以为每个按钮创建一个函数,以便在特定按钮的绑定调用该函数时更改其背景颜色。但是有没有办法将触发绑定的按钮传递给绑定调用的函数?

如果我像这样明确地将要更改的按钮放在绑定中,则我的示例有效:

root.bind_all("<Enter>", lambda e, button = button1: on_enter(e, button))
root.bind_all("<Leave>", lambda e, button = button1: on_leave(e, button))

但我认为必须有一种更优雅的方法来解决此问题,而不是为每个按钮创建一个绑定/函数,当我的程序只有 4 个以上按钮时,这会变得非常烦人。

希望有人给点建议:)

【问题讨论】:

  • 这不是你的 lambda 中的 button 参数吗?为什么需要为每个按钮定义一个函数?
  • @Barmar 是的,参数在那里,但它是空的。除非我手动指定它应该作为参数传递的按钮。是的,这只需要一个功能,但反过来每个按钮都需要绑定。我基本上只是想要一种方法将触发 bind_all 的按钮传递给 bind_all 调用的函数(例如 on_enter)。这样我只需要定义一个函数和一个绑定。

标签: python tkinter


【解决方案1】:

当您将事件绑定到函数时,将使用表示该事件的对象调用该函数。该对象有一个属性widget,它是接收事件的小部件。您无需执行任何其他操作即可获取小部件。

def on_enter(event):
    event.widget.configure(bg="red")

root.bind_all("<Enter>", on_enter)

【讨论】:

    猜你喜欢
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-30
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多