How to bind a key to a button in Tkinter?

Tkinter provides a way to bind the widget to perform certain operations. These operations are defined in a function that can be called by a particular widget. The bind(<button>, function()) method is used to bind the keyboard key to handle such operations. We can also bind a particular key to handle certain events for the button widget.


#Import tkinter library
from tkinter import *
from tkinter import ttk

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

#Set the geometry of tkinter frame
def callback():
   Label(win, text="Hello World!", font=('Georgia 20 bold')).pack(pady=4)

#Create a Label and a Button widget
btn = ttk.Button(win, text="Press Enter to Show a Message", command= callback)

win.bind('<Return>',lambda event:callback())



Executing the above code will display a window that consists of a button.

When we press the "Enter" key, it will show the message on the screen.