Detect keypress in Tkinter in Python
Hello Coders, this tutorial deals with a program to detect keypress using Tkinter in Python.
Before reading this article I recommend you to learn about Event Handling and events raised by any component. Based on that knowledge we always implement the code for those events raised. So I request you to read about those events.
Now coming to the program,
Firstly we need to use one import statement i.e Tkinter package to access all GUI tool kit of Tkinter. Now let is import the package.
from tkinter import Tk,Label
To get a frame, we need to store that in a variable root (example) by calling Tk() function.
root=Tk()
How to Detect keypress in Tkinter in Python
bind() functions are applied to an event where whenever an even is raised the corresponding handler will be called.
root.bind("<Key>",key_pressed)
Here a key_pressed function is called so we need to write a definition of this method.
def key_pressed(event): w=Label(root,text="Key Pressed:"+event.char)
And the final statement.
root.mainloop()
Here is the final program:
from tkinter import Tk, Label root=Tk() def key_pressed(event): w=Label(root,text="Key Pressed:"+event.char) w.place(x=70,y=90) root.bind("<Key>",key_pressed) root.mainloop()
Output:
For any queries please comment below.
Also learn:
hii the above program is good
but, can we have somthing like in a *window has a label consisting text “click spacebar”
n when the user presses the spacebar the user is jumped into new window*
plzz help if someone can
Hi I can help you, I can make the code in like 5 minutes or so. Reply here