Python Windows `msvcrt.getch()` only detects every 3rd keypress?

前端 未结 2 1627
不知归路
不知归路 2020-12-10 08:41

My code is below:

import msvcrt
while True:
    if msvcrt.getch() == \'q\':    
       print \"Q was pressed\"
    elif msvcrt.getch() == \'x\':    
                


        
相关标签:
2条回答
  • 2020-12-10 08:57

    you call the function 3 times in your loop. try calling it only once like this:

    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)
    
    0 讨论(0)
  • 2020-12-10 09:00

    You can optimize things a little bit by also using themsvcrt.kbhit function which will allow you callmsvcrt.getch()only as much as is necessary:

    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
    

    Note that theKey Pressedvalue printed won't make sense for things like function keys. That's because it those cases it's really the Windows scan code for the key, not a regular key code for the character.

    0 讨论(0)
提交回复
热议问题