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

Pygame开发报错:'Ballons' object has no attribute 'image'如何解决

错误原因
  • pygame内置的pygame.sprite.Group.draw()方法有强制要求:所有加入组的Sprite子类实例,必须包含image(存储待绘制的Surface对象)和rect(存储绘制位置的Rect对象)两个固定命名的属性,你在Ballons类中将图片存储到了自定义命名的self.einzel_bild属性,不存在要求的image属性,因此触发属性不存在的报错。
  • 额外存在的逻辑缺陷:你单独定义了self.rect_x、self.rect_y存储位置,但是没有同步赋值给self.rect的对应属性,update方法仅修改了self.rect_y,不会改变最终绘制位置,气球无法正常移动。
修复方案

直接替换你的Ballons类为以下代码即可解决报错和移动问题:

class Ballons(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)     
        # 加载图片后建议加convert_alpha()优化性能,透明背景图也不会出现黑边
        z_bild = pygame.image.load("Bilder/ballons/ballon1.png").convert_alpha()       
        # 按要求赋值给image属性
        self.image = z_bild
        self.rect = self.image.get_rect()
        # 直接修改rect的坐标属性,不需要额外声明自定义位置变量
        self.rect.x = random.randint(100,1800)
        self.rect.y = 700 
        
    def update(self):        
        # 直接修改rect的y坐标,draw方法会自动读取该参数定位绘制
        self.rect.y -=5

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 13:06:05