单击按钮并按Enter时,调用相同的功能 [英] Call the same function when clicking the Button and pressing enter

查看:99
本文介绍了单击按钮并按Enter时,调用相同的功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含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个参数

needs 2 arguments

但是self.enterSubmit函数仅接受一个,因为对于Buttoncommand选项只需要一个.

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()

这篇关于单击按钮并按Enter时,调用相同的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆