我的 python 编辑器在我用 pygame 编写的第一个代码时崩溃了

问题描述 投票:0回答:1

我正在通过 pygame 教程开始 Python 编程。

教程告诉我编写以下代码:-

import pygame

pygame.init()

screen = pygame.display.set_mode((800,400))

当我写完上面的代码后按回车键时,代码就会运行,

并且应该生成一个 800px x 400px 的窗口,不久后自动关闭它。

但是,当我运行此代码时,会生成窗口但不会自动关闭,因此当我通过单击关闭按钮手动关闭它时,窗口崩溃,同时关闭 python 编辑器。

如何解决这个问题?

我向chatGPT寻求解决方案,它给了我下面的代码来尝试:-

import pygame

pygame.init()

screen = pygame.display.set_mode((800, 400))

pygame.quit()

但是,窗口仍然不会自行关闭,从而关闭了整个Python编辑器。

python pygame crash
1个回答
0
投票

您遇到的问题是创建了 pygame 窗口,但您没有正确处理事件循环。事件循环对于捕获关闭窗口等事件是必需的,如果没有它,当您尝试手动关闭窗口时程序会崩溃。 您需要实现一个基本的事件循环来处理事件,例如单击关闭按钮,以便窗口可以优雅地关闭。这是一个简单的实现:

import pygame

# Initialize pygame
pygame.init()

# Set up the screen with dimensions 800x400
screen = pygame.display.set_mode((800, 400))

# Define a variable to control the main loop
running = True

# Start the main loop
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:  # Check if the user closed the window
            running = False  # Exit the loop when the window is closed

# Quit pygame after exiting the loop
pygame.quit()
© www.soinside.com 2019 - 2024. All rights reserved.