python - 使用 PyGame 时处理键盘中断

标签 python pygame

我编写了一个小型 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 导致应用程序终止?

最佳答案

如何将最终循环更改为...:

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

即,确保您捕获键盘中断并将它们视为与退出事件相同。

关于python - 使用 PyGame 时处理键盘中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2819931/

相关文章:

python - 使用 Python 从 OneDrive 下载 Excel 文件会导致文件损坏

python - 贝塞尔曲线与线段的交点

javascript - Pygame解释器

python - 类型错误 : Invalid foreground RGBA argument

python-2.7 - Pygame 会在显示器外用一个矩形 blit Sprite 吗

python - 打字机效果 Pygame

python - 多次更新/删除后谷歌云存储文件卡在时间上

python - SWIG 将 unsigned char * 从 C 返回到 Python

python - 如何扩充部分 zlib 文件

python - DBRefs 可以包含额外的字段吗?