Python如何从命令行获取箭头键

4

我有一个脚本,应该与用户的输入(按箭头键)交互,但我无法获取按键。我尝试了raw_input和其他一些函数,但它们都没有起作用。这是我的示例代码,它应该是什么样子的(运行bool变量可以在另一个函数中设置为False)

running = True
while running:
    #if input == Arrow_UP:
    #    do_Sth
    #elif ...
    display()
    time.sleep(1)

另一个问题是,如何每秒钟只调用一次显示函数,但立即响应输入?

1
可能是重复的问题:https://dev59.com/hHRB5IYBdhLWcg3wyqKo - Xin Yin
嗨,感谢您的回答,但我的第二个问题仍未解决。使用getch(),只有在按下键时才调用显示函数,但我想每秒钟调用它,并在按下键时另外调用另一个函数。 - vtni
@vtni 请单独发布不同的问题。 - chepner
1个回答

7

有不同的情况:

  • 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()

如果要每秒钟调用display()函数,这取决于具体情况。但是,如果您在终端中的单个进程中工作,该进程在等待输入时无法调用display()函数。解决方案是为display()函数使用不同的线程,如下所示:

import threading;

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

display ()

在这里,display会在每次调用时自动向未来延迟一秒。当然,您可以在此调用周围加上一些条件,以便在满足某些条件(例如输入已给出)时停止该进程。请参考此答案进行更全面的讨论。

非常感谢!这是一个终端脚本,所以我不能使用Tkinter,但是您的第二个建议让我用getch解决了问题。在循环之前,我调用了display()函数。 - vtni
我一直在尝试在while循环中使用cv2.waitKey,并在用户按下时使用break,但没有成功,因为我希望代码停止在Selenium上,以便让我手动执行一些操作,然后在没有显式等待的情况下运行,有什么好的想法吗? - Mr-Programs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接