您可以创建一个接受任意数量参数的函数,如下所示:
def clickOrEnterSubmit(self, *args):
#code goes here
这称为任意参数列表。调用者可以随意传入任意数量的参数,并且它们都将被打包到args
元组中。Enter 绑定可以传入它的 1 个event
对象,而 click 命令可以不传入任何参数。
这是一个最小的 Tkinter 示例:
from tkinter import *
def on_click(*args):
print("frob called with {} arguments".format(len(args)))
root = Tk()
root.bind("<Return>", on_click)
b = Button(root, text="Click Me", command=on_click)
b.pack()
root.mainloop()
结果,按下Enter
并单击按钮后:
frob called with 1 arguments
frob called with 0 arguments
如果您不愿意更改回调函数的签名,可以将要绑定的函数包装在lambda
表达式中,并丢弃未使用的变量:
from tkinter import *
def on_click():
print("on_click was called!")
root = Tk()
# The callback will pass in the Event variable,
# but we won't send it to `on_click`
root.bind("<Return>", lambda event: on_click())
b = Button(root, text="Click Me", command=frob)
b.pack()
root.mainloop()