pygame中按时间切换列表内图片触发IndexError索引越界如何解决
错误根因
你的代码抛出IndexError: list index out of range的核心问题是边界判断逻辑和索引取值的执行顺序错误:
- Python列表索引从0开始,你存入了5张图片,
self.images的合法索引范围是0~4,len(self.images)返回值为5。 - 当
self.index +=1后等于5时,你仅设置了done=True和run=False,没有中断后续代码执行,程序会继续运行self.image = self.images[self.index],此时index=5已经超出合法索引范围,直接触发报错。 - 你写的
if self.index > len(self.images)判断永远不会生效:index每次只递增1,最多等于5(和列表长度相等),不可能大于5,所以索引归零的逻辑完全不会执行。
修复方案
场景1:符合你「索引增长到列表末尾就结束游戏」的需求
修改update方法,在触发结束条件后直接中断后续代码执行即可,修改后代码如下:
def update(self, mt): self.current_time += mt if self.current_time >= self.animation_time: self.current_time = 0 self.index += 1 # 触发结束条件 if self.index == len(self.images): done = True run = False # 直接返回,不执行后续的索引取值逻辑 return # 没有触发结束条件时再更新图片 self.image = self.images[self.index]
场景2:如果需要循环播放动画(不需要结束游戏)
直接用取模运算处理边界即可,无需额外判断:
def update(self, mt): self.current_time += mt if self.current_time >= self.animation_time: self.current_time = 0 # 取模运算自动处理边界,索引到最大值后自动归零 self.index = (self.index + 1) % len(self.images) self.image = self.images[self.index]
另外注意你__init__方法里的self.image = images[self.index]写法存在问题:你已经对原始图片做了缩放存入self.images,这里应该改成self.image = self.images[self.index],否则第一张图会是未缩放的原始尺寸。
内容的提问来源于stack exchange,提问作者LR429
相关产品推荐
相关产品推荐

