Joe Wilson
Joe Wilson

Reputation: 77

Pygame: Display not updating until after delay

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?

Upvotes: 5

Views: 724

Answers (1)

sloth
sloth

Reputation: 101052

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()

Upvotes: 4

Related Questions