为什么在使用键盘时我的代码循环两次?

Cai*_*lin 2 python keyboard-python

我正在编写代码,以在输入特定的数字字符串时提醒用户。该代码运行似乎按预期运行,但应给我“ 12345”时输出“ 1122334455”:

import sys
sys.path.append('..')
import keyboard

line = ''
ISBN10 = ''
number = ""

def print_pressed_keys(e):
    global line, ISBN10, number
    line = line.join(str(code) for code in keyboard._pressed_events)
    if line == "2":
        number = 1
    elif line == "3":
        number = 2
    elif line == "4":
        number = 3
    elif line == "5":
        number = 4
    elif line == "6":
        number = 5
    elif line == "7":
        number = 6
    elif line == "8":
        number = 7
    elif line == "9":
        number = 8
    elif line == "10":
        number = 9
    elif line == "11":
        number = 0
    ISBN10 = ISBN10 + str(number)
    if len(ISBN10) > 10:
        ISBN10 = ISBN10[1:11]
    print("ISBN10: " + ISBN10)

keyboard.hook(print_pressed_keys)
keyboard.wait()
Run Code Online (Sandbox Code Playgroud)

输出为:

ISBN10: 1
ISBN10: 11
ISBN10: 112
ISBN10: 1122
ISBN10: 11223
ISBN10: 112233
Run Code Online (Sandbox Code Playgroud)

而应该是:

ISBN10: 1
ISBN10: 12
ISBN10: 123
Run Code Online (Sandbox Code Playgroud)

Aka*_*ph7 5

这是因为keyboard.hook()当您按下某个键释放它时,它将运行其回调。因此,每次按键两次。您仅在按下某个键时才需要运行它:

keyboard.on_press(print_pressed_keys)
# Added hotkey so you can exit block and continue program execution
keyboard.wait("ESC") 
# Run this after you press escape so it stops running the hook when you exit
keyboard.unhook_all() 
Run Code Online (Sandbox Code Playgroud)