为什么 PyGame 中根本没有绘制任何内容?
- 2024-11-25 08:50:00
- admin 原创
- 161
问题描述:
我已经使用 pygame 在 python 中启动了一个新项目,对于背景,我希望下半部分填充灰色,上半部分填充黑色。我以前在项目中使用过矩形绘图,但由于某种原因,它似乎坏了?我不知道我做错了什么。最奇怪的是,每次运行程序时结果都不同。有时只有黑屏,有时灰色矩形覆盖部分屏幕,但从来不会覆盖半个屏幕。
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAY=pygame.display.set_mode((800,800))
pygame.display.set_caption("thing")
pygame.draw.rect(DISPLAY, (200,200,200), pygame.Rect(0,400,800,400))
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
解决方案 1:
您需要更新显示。您实际上是在Surface
对象上绘图。如果您在与 PyGame 显示关联的Surfacepygame.display.update()
上绘图,则这不会立即显示在显示中。当使用或更新显示时,更改将变为可见pygame.display.flip()
。
看pygame.display.flip()
:
这将更新整个显示屏的内容。
虽然pygame.display.flip()
将更新整个显示屏的内容,但pygame.display.update()
允许仅更新屏幕的一部分,而不是整个区域。pygame.display.update()
是针对软件显示的优化版本pygame.display.flip()
,但不适用于硬件加速显示。
典型的 PyGame 应用程序循环必须:
pygame.event.pump()
通过调用或来处理事件pygame.event.get()
。根据输入事件和时间(分别为帧)更新游戏状态和物体的位置
清除整个显示或绘制背景
绘制整个场景(绘制所有对象)
pygame.display.update()
通过调用或来更新显示pygame.display.flip()
限制每秒帧数以限制 CPU 使用率
pygame.time.Clock.tick
import pygame
from pygame.locals import *
pygame.init()
DISPLAY = pygame.display.set_mode((800,800))
pygame.display.set_caption("thing")
clock = pygame.time.Clock()
run = True
while run:
# handle events
for event in pygame.event.get():
if event.type == QUIT:
run = False
# clear display
DISPLAY.fill(0)
# draw scene
pygame.draw.rect(DISPLAY, (200,200,200), pygame.Rect(0,400,800,400))
# update display
pygame.display.flip()
# limit frames per second
clock.tick(60)
pygame.quit()
exit()
 repl.it/@Rabbid76/PyGame-MinimalApplicationLoop
另请参阅事件和应用程序循环
解决方案 2:
只需将您的代码更改为:
import pygame, sys
from pygame.locals import *
pygame.init()
DISPLAY=pygame.display.set_mode((800,800))
pygame.display.set_caption("thing")
pygame.draw.rect(DISPLAY, (200,200,200), pygame.Rect(0,400,800,400))
pygame.display.flip() #Refreshing screen
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
它应该有帮助