单击按钮并按回车时调用相同的函数
问题描述
我有一个具有 Entry
小部件和提交 Button
的 GUI.
I have a GUI that has Entry
widget and a submit Button
.
我基本上是在尝试使用 get()
并打印 Entry
小部件内的值.我想通过单击 submit Button
或按键盘上的 enter 或 return 来执行此操作.
I am basically trying to use get()
and print the values that are inside the Entry
widget. I wanted to do this by clicking the submit Button
or by pressing enter or return on keyboard.
我尝试将 "<Return>"
事件与我按下提交按钮时调用的相同函数绑定:
I tried to bind the "<Return>"
event with the same function that is called when I press the submit Button:
self.bind("<Return>", self.enterSubmit)
但我得到一个错误:
需要 2 个参数
但是 self.enterSubmit
函数只接受一个,因为 Button
的 command
选项只需要一个.
But self.enterSubmit
function only accepts one, since for the command
option of the Button
is required just one.
为了解决这个问题,我尝试创建 2 个功能相同的函数,它们只是具有不同数量的参数.
To solve this, I tried to create 2 functions with identical functionalities, they just have different number of arguments.
有没有更有效的方法来解决这个问题?
Is there a more efficient way of solving this?
解决方案
您可以创建一个接受任意数量参数的函数,如下所示:
You can create a function that takes any number of arguments like this:
def clickOrEnterSubmit(self, *args):
#code goes here
这称为任意参数列表.调用者可以随意传入任意数量的参数,并且它们都将被打包到 args
元组中.Enter 绑定可以传入它的 1 个 event
对象,而 click 命令可以不传入任何参数.
This is called an arbitrary argument list. The caller is free to pass in as many arguments as they wish, and they will all be packed into the args
tuple. The Enter binding may pass in its 1 event
object, and the click command may pass in no arguments.
这是一个最小的 Tkinter 示例:
Here is a minimal Tkinter example:
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
并点击按钮后:
Result, after pressing Enter
and clicking the button:
frob called with 1 arguments
frob called with 0 arguments
如果您不愿意更改回调函数的签名,可以将要绑定的函数包装在 lambda
表达式中,并丢弃未使用的变量:
If you're unwilling to change the signature of the callback function, you can wrap the function you want to bind in a lambda
expression, and discard the unused variable:
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()
相关文章