Python Windows `msvcrt.getch()` 只检测每三个键按下一次?

4 投票
2 回答
25457 浏览
提问于 2025-04-17 22:02

我的代码如下:

import msvcrt
while True:
    if msvcrt.getch() == 'q':    
       print "Q was pressed"
    elif msvcrt.getch() == 'x':    
       sys.exit()
    else:
       print "Key Pressed:" + str(msvcrt.getch()

这段代码是基于 这个问题;我用它来熟悉一下 getch 的用法。

我注意到,要输出一次文本,我需要按键三次。为什么会这样呢?我想把它当作事件循环来用,但这样太慢了...

即使我按下了3个不同的键,它也只会输出第3次按键的结果。

我该怎么做才能让它更快呢?有没有更好的方法来实现我想要的效果?

谢谢!

evamvid

2 个回答

1

你可以通过使用msvcrt.kbhit这个函数来稍微优化一下,这样你就可以根据需要来调用msvcrt.getch(),而不是每次都调用。

while True:
    if msvcrt.kbhit():
        ch = msvcrt.getch()
        if ch in '\x00\xe0':  # arrow or function key prefix?
            ch = msvcrt.getch()  # second call returns the scan code
        if ch == 'q':
           print "Q was pressed"
        elif ch == 'x':
           sys.exit()
        else:
           print "Key Pressed:", ch

需要注意的是,打印出来的Key Pressed值对于像功能键这样的按键来说可能没有意义。这是因为在这些情况下,实际上得到的是Windows的扫描码,而不是普通字符的按键代码。

10

你在循环里调用了这个函数三次。试着像这样只调用一次:

import msvcrt
while True:
    pressedKey = msvcrt.getch()
    if pressedKey == 'q':    
       print "Q was pressed"
    elif pressedKey == 'x':    
       sys.exit()
    else:
       print "Key Pressed:" + str(pressedKey)

撰写回答