Call the same function when clicking the Button and pressing enter

18,869

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

Solution 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()
Share:
18,869

Related videos on Youtube

user2498110
Author by

user2498110

Updated on June 30, 2022

Comments

  • user2498110
    user2498110 almost 2 years

    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?