How to read a single character from the user?

后端 未结 23 2670
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 04:28

Is there a way of reading one single character from the user input? For instance, they press one key at the terminal and it is returned (sort of like getch()).

23条回答
  •  天涯浪人
    2020-11-21 05:03

    If you want to register only one single key press even if the user pressed it for more than once or kept pressing the key longer. To avoid getting multiple pressed inputs use the while loop and pass it.

    import keyboard
    
    while(True):
      if(keyboard.is_pressed('w')):
          s+=1
          while(keyboard.is_pressed('w')):
            pass
      if(keyboard.is_pressed('s')):
          s-=1
          while(keyboard.is_pressed('s')):
            pass
      print(s)
    

提交回复
热议问题