Call the same function when clicking the Button and pressing enter

爷,独闯天下 提交于 2020-01-29 14:56:31

问题


I have a GUI that has Entry widget and a submit Button.

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.

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)

But I got an error:

needs 2 arguments

But self.enterSubmit function only accepts one, since for the command option of the Button is required just one.

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?


回答1:


You can create a function that takes any number of arguments like this:

def clickOrEnterSubmit(self, *args):
    #code goes here

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.

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

Result, after pressing Enter and clicking the button:

frob called with 1 arguments
frob called with 0 arguments

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



回答2:


You could also assign a default value (for example None) for the parameter event. For example:

import tkinter as tk

def on_click(event=None):
    if event is None:
        print("You clicked the button")
    else:
        print("You pressed enter")


root = tk.Tk()
root.bind("<Return>", on_click)
b = tk.Button(root, text='Click Me!', command=on_click)
b.pack()
root.mainloop()


来源:https://stackoverflow.com/questions/17747058/call-the-same-function-when-clicking-the-button-and-pressing-enter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!