【问题标题】:Why is my code looping twice when using keyboard?为什么我的代码在使用键盘时循环两次?
【发布时间】:2019-12-09 07:25:03
【问题描述】:

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

【问题讨论】:

    标签: python keyboard-python


    【解决方案1】:

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

    【讨论】:

    • 感谢完美!谢谢你。我遇到了另一个问题,在 Windows 7 机器上,无论聚焦哪个窗口,程序都会获得输入。然而,在 Windows 10 机器上,当聚焦于不同的窗口时,它不会得到输入。任何想法为什么?
    • @CaiAllin 在他们的page 中他们说:“其他应用程序,例如某些游戏,可能会注册吞下所有关键事件的挂钩。在这种情况下,键盘将无法报告事件。”。我想这取决于当前打开的应用程序以及它们如何处理关键事件。
    • 谷歌搜索了一下,结果发现 Windows 10 上的 UAC 不允许您在没有焦点的情况下获得输入。在我的情况下,解决方法只是以管理员权限运行。另一种方法是降低 UAC 安全性,但我不想对使用计算机的人这样做。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 2019-09-06
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多