Pygame: Display not updating until after delay

前提是你 提交于 2021-02-05 04:59:19

问题


I have a bug in the program I am writing where I first call:

pygame.display.update()

Then I call:

pygame.time.wait(5000)

I want the program to update the display and then wait for a set period of time before continuing. However for some reason the display only updates after the waiting time, not before.

I have attached some example code to demonstrate what is happening:

import pygame
pygame.init()

white = (255,255,255)
black = (0,0,0)
green = (0,255,0)

screenSize = screenWidth, screenHeight = 200, 200
screen = pygame.display.set_mode(screenSize)
screen.fill(white)

pygame.draw.rect(screen, black,((50,50),(50,50)))
pygame.display.update()
pygame.time.wait(5000)

pygame.quit()
raise SystemExit

This should create a white window with black box, then wait 5 seconds and then quit.

However what it actually does is make a window, wait 5 seconds, then for a split second the box will appear, then it immediately quits.

Does anyone know how to fix this problem?


回答1:


Your window's content will only be drawn if your window manager tells your window to actually paint something. So if your code works depends on your window manager.

What you should do to make it work is to let pygame process all events, and you do it usually by calling pygame.event.get().

Also, you should avoid calling blocking functions like pygame.time.wait(), since while they block, you can't handle events or let pygame process system events. That means pygame won't repaint the window, and you can't close the window.

Consider changing your code to this:

import pygame
pygame.init()

white = (255,255,255)
black = (0,0,0)
green = (0,255,0)

screenSize = screenWidth, screenHeight = 200, 200
screen = pygame.display.set_mode(screenSize)
screen.fill(white)

pygame.draw.rect(screen, black,((50,50),(50,50)))

run = True
clock = pygame.time.Clock()
dt = 0
while run:
    dt += clock.tick()
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            run = False
    if dt >= 5000:
        run = False
    pygame.display.update()


来源:https://stackoverflow.com/questions/54687462/pygame-display-not-updating-until-after-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!