使用PyGam时处理键盘中断

2024-06-26 13:41:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个小的Python应用程序,其中我使用PyGame显示一些简单的图形。在

我在应用程序的基础上有一个简单的PyGame循环,如下所示:

stopEvent = Event()

# Just imagine that this eventually sets the stopEvent
# as soon as the program is finished with its task.
disp = SortDisplay(algorithm, stopEvent)

def update():
    """ Update loop; updates the screen every few seconds. """
    while True:
        stopEvent.wait(options.delay)
        disp.update()
        if stopEvent.isSet():
            break
        disp.step()

t = Thread(target=update)
t.start()

while not stopEvent.isSet():
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            stopEvent.set()

对于正常的程序终止来说,它运行得很好;如果PyGame窗口关闭,应用程序关闭;如果应用程序完成任务,应用程序关闭。在

我遇到的问题是,如果我在Python控制台中Ctrl-C,应用程序会抛出一个keyboardInterrupt,但会继续运行。在

因此,问题将是:我在更新循环中做错了什么,如何纠正它,使KeyboardInterrupt导致应用程序终止?在


Tags: theevent应用程序图形ifasupdatepygame
2条回答

把最后一个循环改成

while not stopEvent.isSet():
    try:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                stopEvent.set()
    except KeyboardInterrupt:
        stopEvent.set()

也就是说,确保捕捉到键盘中断并将其视为退出事件。在

修改Alex的回答,请注意,您可能希望对所有异常执行此操作,以确保在主线程因任何原因而失败时关闭线程,而不仅仅是键盘中断。在

您还需要将异常处理程序移出,以避免竞争条件。例如,调用时可能出现键盘中断stopEvent.isSet(). 在

try:
    t = Thread(target=update)
    t.start()

    while not stopEvent.isSet():
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                stopEvent.set()
finally:
    stopEvent.set()

在finally中执行此操作会使问题变得更清楚:无论如何退出此代码块,都可以立即确定事件将始终被设置。(我假设将事件设置两次是无害的。)

如果您不想在KeyboardError上显示堆栈跟踪,您应该捕捉并接受它,但请确保只在最外层的代码中这样做,以确保异常完全传播出去。在

相关问题 更多 >