Call the same function when clicking the Button and pressing enter Call the same function when clicking the Button and pressing enter tkinter tkinter

Call the same function when clicking the Button and pressing enter


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


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

import tkinter as tkdef 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()