4

I was programming pygame in Mac. Then, there was a problem. I wrote the code like below, but pygame.display.update() doesn't work. It should update and wait 3 seconds, but it wait 3 seconds first, and it updates after pygame.quit(). Can anyone tell me how to solve this problem?

this doesn't work:

import pygame
import sys

pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("hello")
font = pygame.font.SysFont("comicsans", 100)
text = font.render("hello", 1, (255, 255, 255))
win.blit(text, (200, 200))
pygame.display.update()
pygame.time.delay(3000)

pygame.quit()
sys.exit(0)

this works normaly:

import pygame
import sys

pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("hello")
font = pygame.font.SysFont("comicsans", 100)
text = font.render("hello", 1, (255, 255, 255))
win.blit(text, (200, 200))
pygame.display.update()

pygame.quit()
pygame.time.delay(3000)
sys.exit(0)

OS: Mac
Python Version 3.8.3
Pygame Version 1.9.6
Editor: Jupyter Notebook

Shim
  • 43
  • 4
  • 1
    This is also similar: https://stackoverflow.com/questions/50219028/pygame-display-update-does-not-update-until-after-clock-delay?rq=1 – The Matt Oct 04 '20 at 02:39

1 Answers1

2

The issue is on MacOS (and potentially other OS's), the screen only updates after pygame events are checked.

Normally, this is done by calling pygame.event.get() or pygame.event.poll().

However, if your program doesn't care about checking events, then a call to pygame.event.pump() will work as well.

This issue is briefly mentioned in the documentation for pygame.event.pump(), link here.

There are important things that must be dealt with internally in the event queue. The main window may need to be repainted or respond to the system. If you fail to make a call to the event queue for too long, the system may decide your program has locked up.

So the solution is to call pygame.event.pump() (or another event function) after pygame.display.update().

That the corrected code would then be:

import pygame
import sys

pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("hello")
font = pygame.font.SysFont("comicsans", 100)
text = font.render("hello", 1, (255, 255, 255))
win.blit(text, (200, 200))
pygame.display.update()
pygame.event.pump() # Make sure events are handled
pygame.time.delay(3000)

pygame.quit()
sys.exit(0)
The Matt
  • 1,423
  • 1
  • 12
  • 22
  • Thanks! But, when I tried this in Atom, it doesn't work. Can you tell me why? – Shim Oct 09 '20 at 01:39
  • Not sure what to tell you. It works for me in Atom, with the script package. Does it work at the command line? Is there an error message? – The Matt Oct 10 '20 at 03:30
  • Sorry, I fixed it! I installed pygame 2.0.0.dev6 and it works! – Shim Oct 10 '20 at 05:50