有没有办法让 pynput.keyboard 计算每次按下(短按和长按)一次,同时可以同时按住多个键?

Is there a way to make pynput.keyboard count every press (short and long) just once with possibility holding multiple keys at once?

我试图在 python 中制作简单的密钥计数器,但我发现了一个问题。当我按住一个键一段时间后,它开始快速计算,因为我按住了这个键。

from pynput.keyboard import Listener
n = 0
def on_press(key):
    global n
    n += 1
def on_release(key):
    pass
with Listener(on_press=on_press, on_release=on_release) as listener:
    listener.join()

所以我做了一个锁,当我按住一个键时,它不能计数。

from pynput.keyboard import Listener
pressed = False
n = 0
def on_press(key):
    global n, pressed
    if pressed == False:
        n += 1
        pressed = True
def on_release(key):
    global pressed
    pressed = False
with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

但现在当我开始打字或玩游戏时,它不会计算每一次按下,因为我有时会同时按住 2 个键,所以 1 个键不被计算在内。

我尝试在按住键 0.5 秒后锁定,所以它会在我打字时计算每次按下,但当我按住多个键超过 0.5 秒时(当我按住多个键更长时间时)仍然存在问题超过 0.5 秒,只算 1).

有没有办法让它对每次按下(无论是否按下)只计算一次,同时可以同时按住多个键?

您的问题可以通过跟踪数组中当前按下的按钮来解决。

from pynput.keyboard import Key, Listener

keys_currently_pressed = []
n = 0

def on_press(key):
    global n
    if key not in keys_currently_pressed:
        keys_currently_pressed.append(key)
        n += 1
        print(key, 'pressed')

def on_release(key):
    global n
    if key in keys_currently_pressed:
        keys_currently_pressed.remove(key)
    print(key, 'released')
    if key == Key.esc:
        print("You pressed", n, "keys")
        return False

with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()