1

I'm coding a little tool that displays the key presses on the screen with Tkinter, useful for screen recording.

Is there a way to get a listener for all key presses of the system globally with Tkinter? (for every keystroke including F1, CTRL, ..., even when the Tkinter window does not have the focus)

I currently know a solution with pyHook.HookManager(), pythoncom.PumpMessages(), and also solutions from Listen for a shortcut (like WIN+A) even if the Python script does not have the focus but is there a 100% tkinter solution?

Indeed, pyhook is only for Python 2, and pyhook3 seems to be abandoned, so I would prefer a built-in Python3 / Tkinter solution for Windows.

Basj
  • 41,386
  • 99
  • 383
  • 673
  • You may are intrested in [this](https://stackoverflow.com/a/69606292/13629335). Its a builtin solution for ms windows. While I like the external libary [pywin32](http://timgolden.me.uk/pywin32-docs/win32api__GetKeyboardState_meth.html). – Thingamabobs Mar 18 '22 at 20:04

2 Answers2

3

Solution 1: if you need to catch keyboard events in your current window, you can use:

from tkinter import *
 
def key_press(event):
    key = event.char
    print(f"'{key}' is pressed")
 
root = Tk()
root.geometry('640x480')
root.bind('<Key>', key_press)
mainloop()

Solution 2: if you want to capture keys regardless of which window has focus, you can use keyboard

Corralien
  • 109,409
  • 8
  • 28
  • 52
0

As suggested in tkinter using two keys at the same time, you can detect all key pressed at the same time with the following:


history = []
def keyup(e):
    print(e.keycode)
    if  e.keycode in history :
        history.pop(history.index(e.keycode))

        var.set(str(history))

def keydown(e):
    if not e.keycode in history :
        history.append(e.keycode)
        var.set(str(history))

root = Tk()
root.bind("<KeyPress>", keydown)
root.bind("<KeyRelease>", keyup)
CarlosSR
  • 1,145
  • 1
  • 10
  • 22
  • Thanks but it seems that this only catch keystrokes if the Tkinter window has the focus (I'm looking for a solution for all keystrokes even if the window doesn't have the focus, see my question) – Basj Mar 18 '22 at 09:03
  • Ah saw the edit. As mentioned in https://stackoverflow.com/questions/57285092/monitor-keypress-in-tkinter-without-focus, you can put the app logic in one thread, and the key detection in another or you can use systemhotkey package – CarlosSR Mar 18 '22 at 09:10