Search code examples
pythonpython-3.xtkintertkinter-entry

How can I detect the pressing of any key on the keyboard in Tkinter?


When the mouse pointer is in the Entry widget, I would like the pressing of any key of the keyboard (without using a loop) to trigger the print: Pressure detected! You pressed any key. What should I write in the function to achieve this? Can you show us a solution with demo code?

Currently in my code, clicking on the Entry widget is detected, but I don't want to get this. I want to get a key press.

import tkinter as tk

def detects_key_press(event):
    print("Pressure detected! You pressed any key")

root = tk.Tk()
entry = tk.Entry(root)
entry.bind("<1>", detects_key_press)
entry.pack(fill="x")

root.mainloop()

Solution

  • Currently, your bind command invokes your function whenever you press "Mouse button 1" (i.e., "<1>"). You'll need to change this to "<Key>". To see what specific key was pressed, you can then access event.char. Make sure to navigate into the Entry field first with a mouse click.

    import tkinter as tk
    
    def detects_key_press(event):
        print(f"Pressure detected! You pressed {event.char}")
    
    root = tk.Tk()
    entry = tk.Entry(root)
    entry.bind("<Key>", detects_key_press)
    entry.pack(fill="x")
    
    root.mainloop()
    

    Demo

    demo key pressed

    See here for a reference to all specific key bindings. E.g., you can specify "<Key-a>" if you only want the event to be invoked on pressing the key a.