Tkinter - 在函数中绑定事件处理



我正在尝试实现一个函数,其中 tk-Button xor 键盘按钮按下正在运行相同的函数。

下面是一个代码示例:

from tkinter import *

root = Tk()
root.geometry("800x600")
root.title("Event Testing")
def on_closing():
root.destroy()
root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)
# root.bind("<Escape>", on_closing)
root.mainloop()

当我绑定<Escape>按钮并按下它时,会引发错误:

TypeError: on_closing() missing 1 required positional argument: 'event'

如果我像def on_closing(event)这样的函数中放入一个event变量,<Escape>按钮可以工作,但 tk-Button 再次引发相同的错误。

有没有更好的选择,然后将<Button-1>绑定到 tk-Button 或创建一个带有event变量的函数和一个没有变量的函数并将其拆分。

编辑:

我想我发现了一个有点丑陋但有效的解决方法。

root_button = Button(root, text="Exit", command=lambda: on_closing(""))

如果还有更好的方法,我想听;)。

这是一个有效的解决方案,我使用了lambda函数而不是on_closing()函数来root.bind()。另一种选择可能是全部在 OOP 中编程。

from tkinter import *

root = Tk()
root.geometry("800x600")
root.title("Event Testing")
def on_closing():
root.destroy()
root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)
root.bind("<Escape>", lambda x: root.destroy())
root.mainloop()

编辑:

好的,再试一次。使用event=None,因此事件定义为默认 none。由于定义,您不会收到错误,并且它是相同的函数。

from tkinter import *
def on_closing(event=None):
root.destroy()
root = Tk()
root.geometry("800x600")
root.title("Event Testing")
root.bind("<Escape>", on_closing)

root_button = Button(root, text="Exit", command=on_closing)
root_button.place(x=400, y=300, anchor=CENTER)
root.mainloop()

最新更新