You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

pygame报错'pygame.Surface' object has no attribute 'rect' 相同逻辑代码此前可正常运行

问题原因

你在变量命名上出现了重复覆盖错误:

  • 前期加载数字资源时,你将one/two/three/four四个变量赋值为pygame.Surface类型的图片对象,此时这四个变量都不具备精灵类才有的rect属性
  • 后续实例化数字精灵时,你仅重新将one变量赋值为自定义Sprite类的实例,two/three/four三个变量仍为之前的Surface对象,直接调用.rect属性就会触发你遇到的报错

修复方案

在数字元素实例化部分,给two/three/four也完成Sprite类的实例化即可,修改后代码如下:

# 数字元素实例化
one = Sprite("one.png")
one.rect.x = 55
one.rect.y = 410
two = Sprite("two.png") # 补充two的实例化代码
two.rect.x = 155
two.rect.y = 410
three = Sprite("three.png") # 补充three的实例化代码
three.rect.x = 255
three.rect.y = 410
four = Sprite("four.png") # 补充four的实例化代码
four.rect.x = 355
four.rect.y = 410
lvlselect.add(one)
lvlselect.add(two)
lvlselect.add(three)
lvlselect.add(four)

额外优化建议

你前期加载的one/two/three/four四个Surface资源没有被实际使用,可以直接删除对应代码,避免后续再出现命名冲突。

内容的提问来源于stack exchange,提问作者user15401554

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:06:07