Pygame技术问题:如何在while循环中仅单次执行每张图片的转换函数
Pygame单张图片仅执行一次转换的实现方案
核心逻辑是通过列表管理待处理图片,配合索引跟踪处理进度,确保每张图片只执行一次转换操作,完成后自动停止并切换场景。
修改后的完整代码
import pygame import os import sys class Main: def __init__(self): pygame.init() self.window = pygame.display.set_mode((0,0), pygame.FULLSCREEN) self.clock = pygame.time.Clock() self.count = 5 # 加载图片并存入列表 self.images_to_convert = [ pygame.image.load(os.path.join("images", "img_one.png")), pygame.image.load(os.path.join("images", "img_two.png")) # 可继续添加更多图片 ] # 跟踪当前处理的图片索引 self.current_img_index = 0 # 定义图片绘制位置(示例,可根据需求调整) self.convert_img_rect = self.window.get_rect() def run(self): while True: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() # 仅当还有未处理的图片时执行转换 if self.current_img_index < len(self.images_to_convert): current_img = self.images_to_convert[self.current_img_index] self.convert_img(current_img) # 处理完当前图片后,索引加1,确保只执行一次 self.current_img_index += 1 else: # 所有图片处理完成,执行场景切换逻辑 self.switch_scene() self.clock.tick(30) def convert_img(self, img): # 清空窗口(可选,避免画面重叠) self.window.fill((0,0,0)) self.window.blit(img, self.convert_img_rect) pygame.display.update() # 这里补全你的图片转换逻辑 if self.count > 0: # 示例转换操作,比如调整图片透明度、缩放等 self.count -= 1 def switch_scene(self): # 场景切换的具体逻辑,比如加载新场景、显示提示等 self.window.fill((255,255,255)) font = pygame.font.Font(None, 72) text = font.render("所有图片处理完成,准备切换场景", True, (0,0,0)) self.window.blit(text, text.get_rect(center=self.window.get_rect().center)) pygame.display.update() if __name__ == "__main__": app = Main() app.run()
关键说明
- 图片列表管理:将所有待处理图片存入
self.images_to_convert列表,便于统一管理和遍历,后续新增图片只需添加到列表即可。 - 索引跟踪:
self.current_img_index记录当前处理到第几张图片,每次处理完成后索引递增,确保每张图片仅执行一次convert_img。 - 场景切换触发:当索引超出列表长度时,说明所有图片处理完成,自动进入
switch_scene方法执行场景切换逻辑。 - 原代码问题修正:补充了缺失的
os、sys导入,定义了convert_img_rect变量,完善了窗口清空和显示更新逻辑。
内容的提问来源于stack exchange,提问作者itt
相关产品推荐
相关产品推荐

