python get arrow keys from command line

前端 未结 1 1638
执念已碎
执念已碎 2021-01-19 08:25

i have a script which should interact with the users input (pressing the arrow keys), but i cannot get the keys. i tried raw_input and some other functions, but they didnt w

相关标签:
1条回答
  • 2021-01-19 09:20

    There are different situations:

    • If you use a graphical frontend such as TKinter or PyGame, you can bind an event to the arrow key and wait for this event.

      Example in Tkinter taken from this answer:

      from Tkinter import *
      
      main = Tk()
      
      def leftKey(event):
          print "Left key pressed"
      
      def rightKey(event):
          print "Right key pressed"
      
      frame = Frame(main, width=100, height=100)
      main.bind('<Left>', leftKey)
      main.bind('<Right>', rightKey)
      frame.pack()
      main.mainloop()
      
    • If your application stays in the terminal, consider using curses as described in this answer

      Curses is designed for creating interfaces that run in terminal (under linux).

    • If you use curses, the content of the terminal will be cleared when you enter the application, and restored when you exit it. If you don't want this behavior, you can use a getch() wrapper, as described in this answer. Once you have initialized getch with getch = _Getch(), you can store the next input using key = getch()

    As to how to call display() every second, it again depends on the situation, but if you work in a single process in a terminal, the process won't be able to call your display() function while it waits for an input. The solution is to use a different thread for the display() function, as in

    import threading;
    
    def display (): 
        threading.Timer(1., display).start ();
        print "display"
    
    display ()
    

    Here display schedules itself one second in the future each time it is called. You can of course put some conditions around this call so that the process stops when some conditions are met, in your case when an input has been given. Refer to this answer for a more thoughout discussion.

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