In this article, we will discuss how to bind all the number keys in Tkinter. Key Binding helps you to create complex GUI applications where you bind some specific key to functions, that executes when that key is pressed.
Syntax:
def key_press(a):
Label(app, text=”You have pressed: ” + a.char, font=’#Text-Font #Text-Size bold’).pack()
for i in range(10):
app.bind(str(i), key_press)
Stepwise Implementation:
Step 1: First of all, import the library Tkinter.
from tkinter import *
Step 2: Now, create a GUI app using Tkinter
app=Tk()
Step 3: Next, give a title and dimensions to the app.
app.title(“#Title you want to assign to app”) app.geometry("#Dimensions of the app")
Step 4: Moreover, make a function to display a message whenever a user presses 0-9 key.
def key_press(a): Label(app, text="You have pressed: " + a.char, font='#Text-Font #Text-Size bold').pack()
Step 5: Further, create a label widget to display some text on the app and display it.
label=Label(app, text="Press any key in the range 0-9") label.pack(padx=#x-axis padding, pady=#y-axis padding) label.config(font='#Text-Font #Text-Size bold')
Step 6: Later on, bind all the number keys, i.e., 0-9 with the callback function.
for i in range(10): app.bind(str(i), key_press)
Step 7: Finally, make an infinite loop for displaying the app on the screen.
app.mainloop()
Example:
Python3
# Python program to bind all # the number keys in Tkinter # Import the library Tkinter from tkinter import * # Create a GUI app app = Tk() # Set the title and geometry of the app app.title( 'Bind Number Keys' ) app.geometry( "800x400" ) # Make a function to display a message # whenever user presses 0-9 key def key_press(a): Label(app, text = "You pressed: " + a.char, font = 'Helvetica 18 bold' ).pack() # Create a label widget to display the text label = Label(app, text = "Press any key in between range 0-9" ) label.pack(pady = 25 ) label.config(font = 'Arial 20 bold' ) # Bind all the number keys with the callback function for i in range ( 10 ): app.bind( str (i), key_press) # Make infinite loop for displaying app on the screen app.mainloop() |
Output: