Call the same function when clicking a Button and pressing Enter in Tkinter


There are various built-in functions, widgets and methods available in the tkinter toolkit library which you can use to build robust and powerful desktop applications. The Button widget in tkinter helps users in creating buttons and performing different actions with the help of its functions. You can also bind the buttons to perform some specific events or callback by using the bind("button", callback) method.


Consider the following example. to create a function that prints a message on the screen whenever the user presses the <Enter> key. To bind the <Enter> key with the function, you can use the bind("<Return>", callback) method.

# Import the required libraries
from tkinter import *

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window

# Define a function to print the message
def print_msg():
   Label(win, text="Hello World!", font=('11')).pack()

# Create a button widget and bind with the given function
win.bind("<Return>", lambda e: print_msg())

button = Button(win, text="Click Me", command=print_msg)



Running the above code will display a window that contains a button. Clicking the button will display the Label widget containing the text in the main window.

Pressing the <Enter> key too would produce the same result. So, we are calling the same function by clicking the button as well as pressing the <Enter> key.

Updated on 16-Dec-2021 10:58:25