Unbuffered character input for python on a windows machine

后端 未结 2 781
轮回少年
轮回少年 2021-01-15 14:45

What I am trying to do

I am trying to design a stopwatch with lap timing. When you press \"L\" then a lap is completed and when you press \"S\" all

相关标签:
2条回答
  • 2021-01-15 15:01

    This is what I've used that seems to work in a Windows console. It's somewhat similar to that ActiveState recipe except that it only works on Windows. It's based on this msdn documentation for _getwch().

    #### windows only ####
    import msvcrt
    
    def readch(echo=True):
        "Get a single character on Windows."
        while msvcrt.kbhit():  # clear out keyboard buffer
            msvcrt.getwch()
        ch = msvcrt.getwch()
        if ch in u'\x00\xe0':  # arrow or function key prefix?
            ch = msvcrt.getwch()  # second call returns the actual key code
        if echo:
            msvcrt.putwch(ch)
        return ch
    
    def pause(prompt='Press any key to continue . . .'):
        if prompt:
            print prompt,
        readch(echo=False)
    

    (Updated to handle Unicode).

    0 讨论(0)
  • 2021-01-15 15:11

    If you are asking about how to read input without input, you probably are looking for binding This requires a Tkinter window, I believe.

    lapEnded = bind_all("<KeyPress-l>", endLap)
    stopRunning = bind_all("<KeyPress-s", noMoreRunning)
    

    Then, you define the functions endLap and noMoreRunning, which do their functions. Depending on your version of Tkinter and/or Python, bind_all may simply be bind. Hope this answers your question.

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