How to bind all the number keys in Tkinter?
Last Updated :
22 Apr, 2022
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
from tkinter import *
app = Tk()
app.title( 'Bind Number Keys' )
app.geometry( "800x400" )
def key_press(a):
Label(app, text = "You pressed: " + a.char,
font = 'Helvetica 18 bold' ).pack()
label = Label(app, text = "Press any key in between range 0-9" )
label.pack(pady = 25 )
label.config(font = 'Arial 20 bold' )
for i in range ( 10 ):
app.bind( str (i), key_press)
app.mainloop()
|
Output:
Share your thoughts in the comments
Please Login to comment...