Pygame精灵绘制崩溃:AttributeError: 'Character'对象无'image'属性
解决Pygame精灵绘制时的AttributeError问题
你的代码里有三个关键错误,导致了AttributeError: 'Character' object has no attribute 'image'的报错,逐一修正即可解决问题:
- 构造函数命名错误:Python类的构造函数必须是双下划线包裹的
__init__,你写的_init_(单下划线)不会被Python识别为构造函数,导致初始化代码完全没执行,Sprite对象自然没有image属性。 - Surface创建参数错误:
pygame.Surface的尺寸参数需要传入元组,你写的pygame.Surface(100,200)会被解析为两个独立参数(宽度100、flags=200),正确写法是pygame.Surface((100,200))。 - fill方法调用错误:
fill是Surface对象的方法,你写成了赋值语句self.image.fill = ("Red"),这会覆盖原方法,正确应该是调用方法self.image.fill("Red")。
修正后的完整代码:
import pygame from sys import exit pygame.init() screen = pygame.display.set_mode((1500,800)) pygame.display.set_caption("Screen") clock = pygame.time.Clock() class Character(pygame.sprite.Sprite): def __init__(self): super().__init__() self.image = pygame.Surface((100,200)) self.image.fill("Red") self.rect = self.image.get_rect() character = pygame.sprite.GroupSingle() character.add(Character()) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() exit() screen.fill((0,0,0)) # 可选:添加背景填充,避免画面残留 character.draw(screen) pygame.display.update() clock.tick(60)
内容的提问来源于stack exchange,提问作者WiseMagician_23
相关产品推荐
相关产品推荐

