How to bind all the number keys in Tkinter?


While developing a Tkinter application, we often encounter cases where we have to perform some specific operation or event with the keystrokes (on keyboard). Tkinter provides a mechanism to deal with such events.

You can use bind(<Key>, callback) function for each widget that you want to bind in order to perform a certain type of event. Whenever we bind a key with an event, the callback event occurs whenever a corresponding key is pressed.

Example

Let's consider an example. Using the bind("", callback) function, we can also bind all the number keys to display a message on the screen such that whenever a user presses a key (1-9), a message will appear on the screen.

# Import required libraries
from tkinter import *

# Create an instance of tkinter window
win = Tk()
win.geometry("700x300")

# Function to display a message whenever a key is pressed
def add_label(e):
   Label(win, text="You have pressed: " + e.char, font='Arial 16 bold').pack()

# Create a label widget
label=Label(win, text="Press any key in the range 0-9")
label.pack(pady=20)
label.config(font='Courier 18 bold')

# Bind all the number keys with the callback function
for i in range(10):
   win.bind(str(i), add_label)

win.mainloop()

Output

Running the above code snippet will display a window with a Label widget.

Whenever you press a key in the range (0-9), it will display a message on the screen.

Updated on: 22-Dec-2021

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements