Tkinter - 使用键绑定调用函数添加变量

Tkinter - Calling a Function With A Keybind Adds A Variable

当我在 Tkinter 中使用 KeyBind 调用方法时,例如parent.bind('<Return>', self.login),当它调用 self.login 时,它似乎添加了第二个变量,就好像它在调用 self.login(var).

虽然它有所不同,但当我让它打印 var 时,它打印了 <Tkinter.Event instance at 0x028C5558>。现在我猜这是调用它的项目或调用它的事件,但是当我让它多次执行时,它显示相同的东西。

通过在键绑定调用的所有方法中添加 var='asdf' 简单地解决了这个问题,但这是否有重要目的?我需要在我的方法中加入什么吗?如果不是,它是做什么用的?

在非常有用的 Effbot Tkinter guide 中,它声明如下(重点是我的):

widget.bind(event, handler)

If an event matching the event description occurs in the widget, the given handler is called with an object describing the event.

您看到的是<Tkinter.Event instance at 0x...>。它有各种属性,描述发生了什么(例如 xy 鼠标指针的位置,widget 本身,等等)。

绑定触发时,它始终会传递一个对象,该对象表示导致回调被调用的事件。它包含事件的 x,y 坐标、按下的键、事件发生时间的时间戳等信息。

您并不总是需要此信息,但它始终会提供给回调。您需要添加一个 event 关键字参数:

def myCallback(event=None):
    <your code here>

...
someWidget.bind("<1>", myCallback)