gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 22:06:57 24 4
gpt4 key购买 nike

我编写了一个小型 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com