【问题标题】:Keypress detection按键检测
【发布时间】:2016-08-01 22:46:48
【问题描述】:

我一直在尝试在 Python 程序中检测按键。我想找到一种不使用 Tkinter、cursesraw_input 的方法来做到这一点。这就是我要说的:

while True:
    if keypressed==1:
        print thekey

有人知道这怎么可能吗?

【问题讨论】:

  • win32api.GetKeyState.
  • “我想找到一种不使用 Tkinter、curses 或 raw_input 的方法来做到这一点”——为什么不呢?是什么让这些工具不受欢迎?如果我们告诉您如何使用 [tool X] 来完成,您是否会说您也想弄清楚如何在没有 [tool X] 的情况下完成它?
  • 同上,不需要每次都重新发明轮子

标签: python keyboard


【解决方案1】:

我冒昧地稍微编辑了您的问题,所以它是有意义的并且有答案,至少在 Windows 上是这样。 (IDLE 仅通过与 tk 的 tkinter 接口与您的键盘交互。)在 Windows 上,答案是使用 msvcrt module's console io functions

import msvcrt as ms

while True:
    if ms.kbhit():
        print(ms.getch())

对于其他系统,您必须找到等效的系统特定调用。对于posix系统,这些可能是curses的一部分,你说你没有使用,但我不知道。

当程序以默认模式从 IDLE 运行时,这些功能无法正常工作。其他图形模式 IDE 可能也是如此。

【讨论】:

    【解决方案2】:

    Python 有一个具有许多功能的 keyboard 模块。安装它,也许用这个命令:

    pip3 install keyboard
    

    然后在如下代码中使用它:

    import keyboard #Using module keyboard
    while True:#making a loop
        try: #used try so that if user pressed other than the given key error will not be shown
            if keyboard.is_pressed('a'): #if key 'a' is pressed 
                print('You Pressed A Key!')
                break #finishing the loop
            else:
                pass
        except:
            break #if user pressed other than the given key the loop will break
    

    可以设置多个Key Detection:

    if keyboard.is_pressed('a') or keyboard.is_pressed('b') or keyboard.is_pressed('c'):
        #then do this
    

    【讨论】:

    • 注意:此模块需要在 Linux 上以 root 身份运行。
    猜你喜欢
    • 2012-10-11
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 1970-01-01
    • 2012-10-10
    • 2014-07-27
    • 2013-12-14
    相关资源
    最近更新 更多