首页 > 解决方案 > 为什么我的 pygame 寡妇在关闭前只保持打开一秒钟?

问题描述

我目前正在关注 YouTube 上的初学者 pygame 教程,即使我完全从教程中复制了代码,我的 pygame 窗口也只会保持打开大约一秒钟然后关闭。

注意:大约三年前有人在这里问过这个问题,但它并没有解决我的问题。我的代码在下面

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')

标签: pythonpygame

解决方案


您的脚本即将结束,因此pygame关闭了所有内容。

您必须创建一个循环才能让您的游戏继续运行,并带有退出循环的条件。

您还需要初始化显示pygame.display.init()

import pygame
pygame.init()
pygame.display.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')

clock = pygame.time.Clock()
FPS = 60  # Frames per second.

# Some shortcuts for colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# For example, display a white rect
rect = pygame.Rect((0, 0), (32, 32))
image = pygame.Surface((32, 32))
image.fill(WHITE)

# Game loop
while True:
    # Ensure game runs at a constant speed
    clock.tick(FPS)

    # 1. Handle events
    for event in pygame.event.get():
        # User pressed the close button ?
        if event.type == pygame.QUIT:
            quit()
            # Close the program. Other methods like 'raise SystemExit' or 'sys.exit()'.
            # Calling 'pygame.quit()' won't close the program! It will just uninitialize the modules.

    # 2. Put updates to the game logic here

    # 3. Render
    win.fill(BLACK)  # first clear the screen
    win.blit(image, rect)  # draw whatever you need
    pygame.display.flip()  # copy to the screen

推荐阅读