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

Pygame分数显示报错:AttributeError: 'pygame.Surface'对象无'get'属性

Pygame分数显示报错:AttributeError: 'pygame.Surface' object has no attribute 'get' 解决方法

嘿,我帮你揪出问题啦!你这个报错完全是代码里的小拼写和变量名失误导致的,咱们一步步修正:

错误原因分析

你代码里有两处明显错误:

  1. 方法调用拼写错误:text_surface.get.rect() 这里写法不对,Pygame Surface的获取矩形方法是get_rect(),你多打了个点,把方法名拆成了get.rect,所以程序找不到get这个属性,直接报错。
  2. 变量名混淆:后面的text.rect.midtop 里,text是你传入的字符串参数,根本没有rect属性,应该用你刚定义的text_rect变量。

修正后的完整代码

def text(self, surface, text, size, x, y):
    font = pg.font.Font(self.font_name, size)
    text_surface = font.render(text, True, WHITE)
    # 修正1:正确调用get_rect()方法
    text_rect = text_surface.get_rect()
    # 修正2:用text_rect而不是text.rect
    text_rect.midtop = (x, y)
    # 可选优化:用传入的surface参数来blit,让函数更通用
    surface.blit(text_surface, text_rect)

额外说明

  • 如果你原本的self.screen就是传入的surface参数,那上面的surface.blit就完全没问题;如果不是,你也可以改回self.screen.blit,但用参数的话函数复用性更强。
  • 以后写Pygame方法的时候要注意,像get_rect()这种是连在一起的方法名,不要随便加标点拆分哦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:46:44