Pygame报错求助:'pygame.rect.Rect'对象无'blit'属性的解决方法
问题解决方法
错误1:screen变量类型错误
你把set_mode()和fill()链式调用了,fill()方法返回的是pygame.Rect对象,而非Surface。blit()是Surface的专属方法,因此会触发属性错误。
修复代码:
# 拆分屏幕创建与背景填充操作 screen = pygame.display.set_mode((552, 640)) screen.fill((182, 210, 214)) #1080, 2340
错误2:Button类初始化逻辑错误
在Button的__init__方法中,直接给self赋值无效,你需要将渲染后的文本Surface存储为实例属性(比如self.image)。否则创建的Button实例并非Surface对象,无法被blit()方法调用。
修复后的Button类:
class Button: def __init__(self, symbol, buttonsprite=['Images/Button/Clicked.png','Images/Button/Not_clicked.png'], size=40, around=True, color=(0, 0, 0)): # 将渲染后的文本存入实例属性 self.image = text(size).render(symbol, around, color)
错误3:渲染与屏幕更新顺序颠倒
当前代码先执行pygame.display.update()再绘制按钮,导致绘制内容无法被显示。必须先完成所有绘制操作,再更新屏幕。
修复后的主循环:
run = True while run: # 优先处理事件 for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() run = False # 重新填充背景,避免帧残留 screen.fill((182, 210, 214)) # 绘制按钮 button_y = 384 button_x = 10 for idx, btn in enumerate(buttons): # 使用enumerate获取索引,比buttons.index(i)更高效且避免重复元素出错 screen.blit(btn.image, (button_x + 60*idx, button_y)) # 最后更新屏幕 pygame.display.update()
额外优化建议
- 用
enumerate()遍历按钮获取索引,比buttons.index(i)效率更高,且能避免列表存在重复元素时的索引错误。 - 主循环内每次绘制前重新填充背景,防止之前的绘制内容残留导致画面混乱。
内容的提问来源于stack exchange,提问作者Human
相关产品推荐
相关产品推荐

