【问题标题】:Python module: keyboard.read executing commands twicePython 模块:keyboard.read 执行命令两次
【发布时间】:2021-11-18 15:52:08
【问题描述】:

我编写的程序是一个菜单,可通过键盘模块的实时键盘输入进行导航;与在 python 中创建的通过设置用户输入(input())导航的标准菜单不同,此菜单在使用时应该具有类似滚动的效果。 代码:

def MenuInterface():
    import keyboard
    MenuList = ["""Welcome to Empires Shell
    > [PLAY]
    [HELP]
    [CREDITS]
    [EXIT]
    """, """Welcome to Empires Shell
    [PLAY]
    > [HELP]
    [CREDITS]
    [EXIT]""", """Welcome to Empires Shell
    [PLAY]
    [HELP]
    > [CREDITS]
    [EXIT]
    """, """Welcome to Empires Shell
    [PLAY]
    [HELP]
    [CREDITS]
    > [EXIT]
    """]
    print (MenuList[0])
    x = 0
    while True: #This is the actual loop where I'm encountering my error
        if keyboard.read_key() == "s":
            x = x + 1
            if x == -1:
                x = 3
                print (MenuList[x])
            elif x == 4:
                x = 0
                print (MenuList[x])
            else:
                print (MenuList[x])
       


MenuInterface()

跑步回报:

Welcome to Empires Shell
    > [PLAY]
    [HELP]
    [CREDITS]
    [EXIT]

在shell中输入“s”后,返回:

Welcome to Empires Shell
    [PLAY]
    > [HELP]
    [CREDITS]
    [EXIT]
Welcome to Empires Shell
    [PLAY]
    [HELP]
    > [CREDITS]
    [EXIT]

如您所见,keyboard.read 为单个输入运行了两次。你知道为什么吗?如果是这样,我该如何解决这个问题? 谢谢!

【问题讨论】:

    标签: python-3.x function input module


    【解决方案1】:

    keyboard.read_key() 的描述是:

    在键盘事件发生之前一直阻塞,然后返回该事件的名称,如果缺少,则返回其扫描码。

    此函数返回原始键盘扫描码,这意味着它将返回单个按键的按下和释放(包括修饰键,如 ShiftControl)。这种类型的细节通常在操作系统级别处理,应用程序从中接收实际的字符或控制代码。

    您可能想要的是使用内置的input() 函数,或者如果您想要更高级别的东西,可以使用来自外部库的工具,例如click.prompt()

    这两个函数都需要回车并接受多个字符。如果您想对输入的每个字符立即采取行动,请参阅this question

    【讨论】:

      猜你喜欢
      • 2014-01-27
      • 2020-05-05
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 2017-05-01
      • 1970-01-01
      • 2014-05-12
      • 2019-07-05
      相关资源
      最近更新 更多