How to read a single character from the user?

后端 未结 23 2776
爱一瞬间的悲伤
爱一瞬间的悲伤 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:12

    Answered here: raw_input in python without pressing enter

    Use this code-

    from tkinter import Tk, Frame
    
    
    def __set_key(e, root):
        """
        e - event with attribute 'char', the released key
        """
        global key_pressed
        if e.char:
            key_pressed = e.char
            root.destroy()
    
    
    def get_key(msg="Press any key ...", time_to_sleep=3):
        """
        msg - set to empty string if you don't want to print anything
        time_to_sleep - default 3 seconds
        """
        global key_pressed
        if msg:
            print(msg)
        key_pressed = None
        root = Tk()
        root.overrideredirect(True)
        frame = Frame(root, width=0, height=0)
        frame.bind("", lambda f: __set_key(f, root))
        frame.pack()
        root.focus_set()
        frame.focus_set()
        frame.focus_force()  # doesn't work in a while loop without it
        root.after(time_to_sleep * 1000, func=root.destroy)
        root.mainloop()
        root = None  # just in case
        return key_pressed
    
    
    def __main():
            c = None
            while not c:
                    c = get_key("Choose your weapon ... ", 2)
            print(c)
    
    if __name__ == "__main__":
        __main()
    

    Reference: https://github.com/unfor19/mg-tools/blob/master/mgtools/get_key_pressed.py

提交回复
热议问题