How to read a single character from the user?

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

    This is NON-BLOCKING, reads a key and and stores it in keypress.key.

    import Tkinter as tk
    
    
    class Keypress:
        def __init__(self):
            self.root = tk.Tk()
            self.root.geometry('300x200')
            self.root.bind('', self.onKeyPress)
    
        def onKeyPress(self, event):
            self.key = event.char
    
        def __eq__(self, other):
            return self.key == other
    
        def __str__(self):
            return self.key
    

    in your programm

    keypress = Keypress()
    
    while something:
       do something
       if keypress == 'c':
            break
       elif keypress == 'i': 
           print('info')
       else:
           print("i dont understand %s" % keypress)
    

提交回复
热议问题