首页 > 解决方案 > pygame.display.update() 不能正常工作

问题描述

我在 Mac 上编程 pygame。然后,出现了问题。我编写了如下代码,但 pygame.display.update() 不起作用。它应该更新并等待 3 秒,但它先等待 3 秒,然后在 pygame.quit() 之后更新。谁能告诉我如何解决这个问题?

这不起作用:

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)

这工作正常:

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)

操作系统:Mac
Python 版本 3.8.3
Pygame 版本 1.9.6
编辑器:Jupyter Notebook

标签: pythonpython-3.xpygame

解决方案


问题出在 MacOS(可能还有其他操作系统)上,屏幕仅在检查 pygame 事件后才会更新。

通常,这是通过调用pygame.event.get()or来完成的pygame.event.poll()

但是,如果您的程序不关心检查事件,那么调用 topygame.event.pump()也可以。

文档中简要提到了这个问题pygame.event.pump()链接在这里

有一些重要的事情必须在事件队列内部处理。主窗口可能需要重新绘制或响应系统。如果您长时间未能调用事件队列,系统可能会判定您的程序已锁定。

所以解决方案是pygame.event.pump()pygame.display.update().

更正后的代码将是:

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)

推荐阅读