gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 21:31:56 24 4
gpt4 key购买 nike

我正在编写代码以在输入特定数字字符串时提醒用户。代码运行似乎按预期运行,但在应该给我“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()

输出是:

ISBN10: 1
ISBN10: 11
ISBN10: 112
ISBN10: 1122
ISBN10: 11223
ISBN10: 112233

而它应该是:

ISBN10: 1
ISBN10: 12
ISBN10: 123

最佳答案

这是因为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()

关于python - 为什么我的代码在使用键盘时循环两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57296450/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com