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

Pygame:为Rect类实例按钮添加自定义文本时遇属性错误

解决Pygame按钮文本自定义的AttributeError问题

嘿,我一眼就看到问题出在哪啦!你现在的报错是因为把按钮文本的参数名和字体对象搞混了,咱们一步步来修正:

错误根源分析

你在Button类的__init__方法里,把接收按钮文本的参数命名成了font,但你创建按钮实例时传的是'One'、'Two'这类字符串。然后你又写了self.font = font.pygame.freetype.SysFont('Arial', 25)——这里的font是你传的文本字符串,它当然没有pygame属性,所以就抛出了AttributeError。

另外还有两个小问题:

  • draw方法里的渲染坐标是固定的(42,25),这样所有按钮的文本都会叠在一起
  • 渲染时把self.font(字体对象)当成文本内容传进去了,这也不对

修正后的完整代码

import pygame
import sys
import pygame.freetype

pygame.display.init()
pygame.freetype.init()
width = 300
height = 350
bg = (255, 255, 255)
screen = pygame.display.set_mode((width, height))
screen.fill(bg)

# 先初始化全局字体(所有按钮可以共用这个字体,避免重复创建)
button_font = pygame.freetype.SysFont('Arial', 25)

class Button:
    def __init__(self, rect_x, rect_y, rect_width, rect_height, text):
        # 存储按钮的矩形参数,用Pygame的Rect类更方便
        self.rect = pygame.Rect(rect_x, rect_y, rect_width, rect_height)
        # 存储当前按钮的专属文本内容
        self.text = text
        # 共用全局字体(也可以在这里单独创建字体,按需调整)
        self.font = button_font

    def draw(self):
        # 绘制按钮背景矩形
        pygame.draw.rect(screen, (200, 200, 200), self.rect)
        # 计算文本居中的坐标:按钮中心减去文本尺寸的一半
        text_surface, text_rect = self.font.render(self.text, (0,0,0))  # 黑色文本
        text_pos = (
            self.rect.centerx - text_rect.width // 2,
            self.rect.centery - text_rect.height // 2
        )
        # 把文本渲染到按钮的居中位置
        self.font.render_to(screen, text_pos, self.text, (0,0,0))

# 创建带不同文本的按钮实例
button1 = Button(10, 10, 100, 50, 'One')
button2 = Button(10, 70, 100, 50, 'Two')
button3 = Button(10, 130, 100, 50, 'Three')

# 游戏主循环
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    
    # 每次循环重绘背景,避免多次渲染导致文本重叠
    screen.fill(bg)
    button1.draw()
    button2.draw()
    button3.draw()
    pygame.display.update()

关键修改点说明

  • 把__init__的参数从font改成了text,明确区分文本内容和字体对象
  • 使用pygame.Rect管理按钮的位置和尺寸,更符合Pygame的使用习惯
  • 全局初始化字体,让所有按钮共用,节省资源
  • 计算文本的居中位置,确保每个按钮的文本都在自己的按钮中央
  • 修复了渲染文本时的参数错误,把文本内容self.text正确传给render_to
  • 每次循环重绘背景,避免多次渲染导致文本重叠

这样修改后,每个按钮就能显示自己的自定义文本啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 09:42:45