python - 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
解决方案
问题出在 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)
推荐阅读
- java - 杰克逊重用对象忽略了使用java的rest请求中的一些属性
- tensorflow - 卷积网络作为特征提取器
- javascript - 如何更改动态表中的特定图像?
- download - 当我按下下载它应该生成payslip pdf,但显示TCPDF ERROR: Some data has been output, can't send PDF file
- reactjs - 警告:使用 react-bootstrap 导航栏时,在 StrictMode 中不推荐使用 findDOMNode
- r - 从频率表到观测
- android - Kotlin codelab:没有返回值,那为什么返回泛型类型?
- sql - 如何使用 SQL/Access 基于公共分组在表中重新排序序列号(不是 id)?
- python - 在 Python 中使用辛欧拉模拟地球轨道
- php - 如果在 WooCommerce 中自动添加包装,则在选择产品重量时不计算最终成本