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

pygame运行报错AttributeError: 'pygame.Surface' object has no attribute 'rect'求助

报错原因
  • 核心错误出现在draw_lives函数中img.rect.x = x + 30 * i、img.rect.y = y两行代码
  • 你传入draw_lives的第四个参数ball_mini_img是pygame.Surface类型对象,Surface本身没有内置rect属性,只有pygame.sprite.Sprite子类的实例才会自定义rect属性。你已经通过img.get_rect()得到了坐标对象img_rect,却错误尝试访问Surface不存在的rect属性,因此触发报错。
  • 额外存在的代码隐患:
    1. Gates类中update、hide方法缩进错误,当前缩进在__init__方法内部,属于实例的局部函数,无法被精灵组调用
    2. __init__中self.hide_timer =和pygame.time.get_ticks()错误拆分为两行,会直接触发语法错误
    3. update方法中引用的y是__init__的局部参数,超出作用域无法访问
    4. draw_lives的函数调用缩进在函数定义内部,永远不会被执行
修复方案
  1. 修正draw_lives函数逻辑和缩进:
def draw_lives(surf, x, y, lives, img):
    for i in range(lives):
        img_rect = img.get_rect()
        # 修改get_rect返回的坐标对象,不要访问Surface不存在的rect属性
        img_rect.x = x + 30 * i
        img_rect.y = y
        surf.blit(img, img_rect)

# 函数调用放在全局作用域,不要缩进在draw_lives内部
draw_lives(screen, WIDTH - 100, 5, gate1.lives, ball_mini_img)
draw_lives(screen, WIDTH - 100, HEIGHT - 5, gate2.lives, ball_mini_img)
  1. 修正Gates类的代码问题:
class Gates(pygame.sprite.Sprite):
  def __init__(self, y, h):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.Surface((400,15))
    self.image.fill((random.randrange(0, 33),random.randrange(0,41),random.randrange(0, 57)))
    self.rect = self.image.get_rect()
    self.rect.x = WIDTH/2 - 200
    self.rect.y = y
    # 将y、h存为实例属性,供其他方法调用
    self.y = y
    self.h = h
    self.lives = 5
    self.hidden = False
    # 修复赋值换行问题
    self.hide_timer = pygame.time.get_ticks()

  # 方法缩进和__init__同级
  def update(self):
      #Show if hidden
      if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000:
          self.hidden = False
          self.rect.x = WIDTH/2 - 200
          # 调用实例属性self.y
          self.rect.y = self.y

  def hide(self):
      #Hide the Gates
      self.hidden = True
      self.hide_timer = pygame.time.get_ticks()
      # 调用实例属性self.h
      self.rect.center = (WIDTH/2, self.h)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 21:12:03