如何停止pygame窗口冻结?

时间:2020-04-06 05:45:44

标签: python python-3.x pygame

当我运行代码时,蓝色rect会显示在其正确位置,但是整个窗口会冻结并最终崩溃。我怎样才能解决这个问题?

import pygame
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")
run = True
while run:
    pygame.time.delay(100)
    filled_rect = pygame.Rect(100, 100, 25, 25)

    pygame.draw.rect(win, (0,0,255), filled_rect)
    pygame.display.update()

1 个答案:

答案 0 :(得分:1)

您必须添加一个事件循环。通过pygame.event.pump()pygame.event.get()处理事件。因此,将处理IO和内部事件,并且窗口将保持响应。例如:

import pygame

win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")

run = True
while run:
    pygame.time.delay(100)

    # handle events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # clear the disaply
    win.fill(0)

    # draw the scene
    filled_rect = pygame.Rect(100, 100, 25, 25)
    pygame.draw.rect(win, (0,0,255), filled_rect)

    # update the dispaly
    pygame.display.update()

pygame.quit()