如何使用 Python 中的键盘模块收听按下的键的名称?

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

我想使用 Python keyboard module 获取按下的键的名称。

我可以通过以下方式注册热键。

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()

但是,除非我提前注册热键,否则上面的代码不会响应。

即使是未注册为热键的击键,我也想获取名称。

这是因为我想要一个 TextInput 以便用户可以在 GUI 中注册热键。

在键盘模块中,我可以监听未注册为热键的击键吗?

尝试 keyboard.record 函数 here

例如,

events = keyboard.record('esc')

记录了我所有的击键,直到我按下退出键。 keyboard.record returns KeyboardEvent 对象的列表,其中包含按下的键的名称(以及一些其他数据)。

在我输入的情况下,events[0].name returns 'h' 这是我输入的第一个键,events[2].name returns e 这是我输入的第二个键,等等

请注意,向上键和向下键被记录为单独的 KeyboardEvent,因此您可能希望过滤它们,因为它包含每个字母的双倍(假设您只关心名称) .

替代方法: 如果您未与 keyboard 结婚,我建议您查看 pynput,我已经使用此软件包成功构建了键盘记录器。