Surface.fill()无法清空显示的Pygame开发问题求助
Pygame 中 Surface 内容无法清除的问题解决
问题根源
你遇到的问题核心在于:box 是一个独立的 持久化Surface,一旦将红色Surface绘制到它上面,box 的像素数据就会永久改变。而 screen.fill(WHITE) 仅会清空屏幕Surface,不会重置 box 内部的内容,因此每次将 box 绘制到屏幕上时,之前的红色内容都会被保留。
解决方案
根据你的需求,提供两种常见解决思路:
1. 仅在事件触发帧显示红色方块(自动消失)
如果希望红色方块仅在定时器触发的那一帧显示,之后自动消失,需要每次循环重新初始化 box 的内容:
import pygame as pg pg.init() GREEN, WHITE, RED = (60, 120, 60), (255,255,255), (120, 60, 60) screen = pg.display.set_mode((200, 200)) # 初始化空的box Surface box = pg.Surface((150, 150)) running = True EVENT_SECOND_TIMER = pg.event.custom_type() pg.time.set_timer(EVENT_SECOND_TIMER, 1000) show_red = False while running: screen.fill(WHITE) for event in pg.event.get(): if event.type == pg.QUIT: running = False # 触发定时器时标记需要显示红色 if event.type == EVENT_SECOND_TIMER: show_red = True # 每次循环先重置box为绿色 box.fill(GREEN) if show_red: surf = pg.Surface((50,50)) surf.fill(RED) box.blit(surf, (50, 50)) show_red = False # 显示后重置标记,下一帧不再显示 screen.blit(box, (25, 25)) pg.display.update() pg.quit()
2. 保留红色方块,按需清除
如果希望红色方块保留到主动触发清除操作时再消失,可以在需要清除的时机重新填充 box 为绿色:
import pygame as pg pg.init() GREEN, WHITE, RED = (60, 120, 60), (255,255,255), (120, 60, 60) screen = pg.display.set_mode((200, 200)) box = pg.Surface((150, 150)) box.fill(GREEN) running = True EVENT_SECOND_TIMER = pg.event.custom_type() EVENT_CLEAR_RED = pg.event.custom_type() pg.time.set_timer(EVENT_SECOND_TIMER, 1000) pg.time.set_timer(EVENT_CLEAR_RED, 3000) # 3秒后自动清除红色 while running: screen.fill(WHITE) for event in pg.event.get(): if event.type == pg.QUIT: running = False if event.type == EVENT_SECOND_TIMER: surf = pg.Surface((50,50)) surf.fill(RED) box.blit(surf, (50, 50)) # 触发清除事件时重置box if event.type == EVENT_CLEAR_RED: box.fill(GREEN) screen.blit(box, (25, 25)) pg.display.update() pg.quit()
关键要点
- Pygame 的 Surface 是独立的像素容器,修改后内容会永久保留,除非主动调用
fill()或其他像素修改方法。 screen.fill()仅作用于屏幕Surface,对自定义Surface(如box)无效。- 要实现帧间内容清除,需确保每次绘制前,目标Surface已被重置为初始状态,或通过状态变量控制临时内容的显示。
内容的提问来源于stack exchange,提问作者Owen Meyer
相关产品推荐
相关产品推荐

