Pygame报错:module 'pygame.surface'无'get_rect'属性 求助
解决:AttributeError: module 'pygame.surface' has no attribute 'get_rect'
错误根源
你给红色区域赋值时写了self.image = pygame.surface,这把pygame.surface模块赋值给了self.image,而不是创建一个可操作的Surface实例。模块本身没有get_rect()方法,因此触发错误。
修复方法
你需要创建实际的纯色Surface来替代PNG,或者直接用pygame.draw.rect绘制矩形,两种方案如下:
方案1:创建纯色Surface(兼容原有blit逻辑)
修改Region类中红色区域的代码,创建指定大小的Surface并填充颜色:
class Region: def __init__(self, x, y, colour): self.x = x self.y = y self.colour = colour # 自定义矩形的宽高,按需调整 rect_size = (100, 100) if self.colour == "red": # 创建Surface实例并填充红色 self.image = pygame.Surface(rect_size) self.image.fill("red") elif self.colour == "blue": self.image = pygame.image.load("/Users/wallera/PycharmProjects/MAJORPROJECT2/Assets/square_blue_region1.png") # 可选:添加convert_alpha()处理透明通道 # self.image = pygame.image.load("路径").convert_alpha() else: print(f"Unknown colour: {self.colour}") # 创建默认Surface避免后续报错 self.image = pygame.Surface(rect_size) self.image.fill("gray") self.rect = self.image.get_rect() self.rect.topright = (self.x, self.y) def draw(self, screen): screen.blit(self.image, self.rect)
方案2:直接绘制矩形(更轻量化)
如果不需要依赖Surface,直接在draw方法中绘制矩形,省去Surface创建步骤:
class Region: def __init__(self, x, y, colour): self.x = x self.y = y self.colour = colour # 定义矩形尺寸 self.rect = pygame.Rect(0, 0, 100, 100) self.rect.topright = (self.x, self.y) def draw(self, screen): # 直接绘制矩形到屏幕 pygame.draw.rect(screen, self.colour, self.rect)
注意事项
- 区分
pygame.Surface()(大写开头的类,用于创建实例)和pygame.surface(小写的模块),不要混淆。 - 加载PNG时如果有透明背景,建议使用
convert_alpha()方法优化显示效果。
内容的提问来源于stack exchange,提问作者AlexanderWaller
相关产品推荐
相关产品推荐

