Search code examples
pythonkeyboard

How to listen the name of a pressed key using the Keyboard module in Python?


I want to get the name of the key pressed using the Python keyboard module.

I was able to register the hotkey in the following way.

import tkinter as tk
import threading
import time
import keyboard 

class threadingGUI():
    def __init__(self):
        self.stop_flag=False
        self.thread=None

    def executeHotKey(self,abc):
        print("key pressed " + abc)

    def time_count(self):
        while not self.stop_flag:
            time.sleep(1)

    def start(self):
        if not self.thread:
            #add hotkey
            keyboard.add_hotkey('a', self.executeHotKey, args=('a'))
            keyboard.add_hotkey('b', self.executeHotKey, args=('b'))
            keyboard.add_hotkey('c', self.executeHotKey, args=('c')) 
            self.thread = threading.Thread(target=self.time_count)
            self.stop_flag=False
            self.thread.start()


    def stop(self):
        if self.thread:
            self.stop_flag=True
            self.thread.join()
            self.thread=None

    def GUI_start(self):
        root=tk.Tk()
        Button001=tk.Button(root,text="Start",command=self.start)
        Button001.pack()
        Button002=tk.Button(root,text="Stop",command=self.stop)
        Button002.pack()
        root.mainloop()

        self.stop_flag=True
        self.thread.join()

t = threadingGUI()
t.GUI_start()

However, the above code won't respond unless I register the hotkey in advance.

I want to get the name even for keystrokes that don't register as hotkeys.

This is because I want to have a TextInput so that users can register hotkeys in the GUI.

In the Keyboard module, can I listen for keystrokes that are not registered as hotkeys?


Solution

  • Try the keyboard.record function as shown here.

    For example,

    events = keyboard.record('esc')
    

    recorded all my keystrokes until I pressed the escape key. keyboard.record returns a list of KeyboardEvent objects which contain the names (as well as some other data) for the pressed keys.

    In the case of what I typed, events[0].name returns 'h' which was the first key I typed, events[2].name returns e which was the second key I typed, etc.

    Note that key up and key down are recorded as separate KeyboardEvent's so you will likely want to filter them as it will contain doubles of each letter (assuming the name is all you are concerned with).

    Alternate approach: If you aren't married to keyboard, I suggest checking out pynput, I've had some great success building keyloggers using this package.