PYGame - 如何通过按键停止和关闭窗口?

问题描述

我使用 PYGAME 创建了一个脚本来为钟摆运动模拟设置动画。我想按“q”键停止模拟并关闭窗口。我尝试了许多不同的代码,但都返回了一些错误代码事件部分的最低版本是:

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
            
        if event.type == KEYDOWN:
            if event.key == K_t:
                is_tracing = not(is_tracing)
            if event.key == K_c:
                trace.fill(WHITE)
            if event.key == K_q:
                done = True
        break

“c”和“t”事件正在运行,“q”想法停止模拟,但模拟窗口冻结,我需要重新启动内核才能让它再次运行。知道如何在不杀死内核的情况下关闭窗口吗?

我正在使用 Anaconda Navigator 1.10 和 Python 3.8.5 在 Jupter Notebook 6.1.4 上运行代码

解决方法

知道如何在不杀死内核的情况下关闭窗口吗?

尝试使用 pygame.quit()。来自pygame FAQ

确保在退出应用程序或游戏时调用 pygame.quit()。

# ... running = True
while running:
    event = pygame.event.wait ()
    if event.type == pygame.QUIT:
        running = False  # Be IDLE friendly
pygame.quit ()