- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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 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()
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.
- Related Articles
- How to bind the Enter key to a tkinter window?
- How to bind the Escape key to close a window in Tkinter?
- How to bind the spacebar key to a certain method in Tkinter?
- How do I bind the enter key to a function in Tkinter?
- How to bind a Tkinter event to the left mouse button being held down?
- How to bind a click event to a Canvas in Tkinter?
- How to bind multiple events with one "bind" in Tkinter?
- Call a Function with a Button or a Key in Tkinter
- How to bind to shift+tab in Tkinter?
- How to Disable / Enable a Button in TKinter?
- How to update a Button widget in Tkinter?
- How to highlight a tkinter button in macOS?
- How to create a Tkinter toggle button?
- How to bind events to Tkinter Canvas items?
- How to pass arguments to a Button command in Tkinter?