python - Call the same function when clicking the Button and pressing enter -


i have gui has entry widget , submit button.

i trying use get() , print values inside entry widget. wanted clicking submit button or pressing enter or return on keyboard.

i tried bind "<return>" event same function called when press submit button:

self.bind("<return>", self.entersubmit) 

but got error:

needs 2 arguments

but self.entersubmit function accepts one, since command option of button required one.

to solve this, tried create 2 functions identical functionalities, have different number of arguments.

is there more efficient way of solving this?

you can create function takes number of arguments this:

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

this called arbitrary argument list. caller free pass in many arguments wish, , packed args tuple. enter binding may pass in 1 event object, , click command may pass in no arguments.

here minimal tkinter example:

from tkinter import *  def on_click(*args):     print("frob called {} 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 , clicking button:

frob called 1 arguments frob called 0 arguments 

if you're unwilling change signature of callback function, can wrap function want bind in lambda expression, , discard unused variable:

from tkinter import *  def on_click():     print("on_click called!")  root = tk()  # callback pass in event variable,  # won't send `on_click` root.bind("<return>", lambda event: on_click()) b = button(root, text="click me", command=frob) b.pack()  root.mainloop() 

Comments