How to bind a key to a button in Tkinter?

PythonTkinterServer Side ProgrammingProgramming

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.

Example

#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
win.geometry("750x250")
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)
btn.pack(ipadx=10)

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

win.mainloop()

Output

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.

raja
Published on 21-Apr-2021 07:46:43
Advertisements