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:

Detect keypress in Tkinter in Python

For any queries please comment below.

Also learn:

Leave a Reply

Your email address will not be published. Required fields are marked *