Pygame - 添加文本到 rect 的 class 实例

Pygame - add text to class instance of a rect

我正在尝试向 class 个矩形实例添加文本。

我已经能够通过在 class 之外设置“字体”变量并将所需的文本放入绘图函数中的“font.render_to”来做到这一点,但这意味着文本将与 class.

中设置的所有按钮相同

我想为 class 实例(button1、button2、button3)中指定的每个按钮设置不同的文本,如下面的代码所示,但我收到以下错误:

Traceback (most recent call last):
File "path_to_file/test.py", line 30, in <module>
button1 = Button(10, 10, 100, 50, 'One')
File "path_to_file/test.py", line 23, in __init__
self.font = font.pygame.freetype.SysFont('Arial', 25)
AttributeError: 'str' object has no attribute 'pygame'.

代码:

import pygame
import sys
import pygame.freetype


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

# Sets the window size
screen = pygame.display.set_mode((width, height))

# Sets the background colour to white
screen.fill(bg)


# Button class - All buttons are created using the below parameters
class Button:

    def __init__(self, rect_x, rect_y, rect_width, rect_height, font):
        self.rect_x = rect_x
        self.rect_y = rect_y
        self.rect_width = rect_width
        self.rect_height = rect_height
        self.font = font.pygame.freetype.SysFont('Arial', 25)

# Draw function - Creates the rectangle and adds text
    def draw(self):
        pygame.draw.rect(screen, (200, 200, 200), (self.rect_x, self.rect_y, self.rect_width, self.rect_height))
        self.font.render_to(screen, (42, 25), self.font, bg)


# Class instances - Defines button size and location in the PyGame window
button1 = Button(10, 10, 100, 50, 'One')
button2 = Button(10, 70, 100, 50, 'Two')
button3 = Button(10, 130, 100, 50, 'Three')

# game loop
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    button1.draw()
    button2.draw()
    button3.draw()
    pygame.display.update()

构造函数的第5个参数是文本。您必须将文本存储在属性中并呈现文本。 font.pygame.freetype.SysFont('Arial', 25) 没有任何意义。字体对象由pygame.freetype.SysFont('Arial', 25)构造。 render_to的目标位置取决于按钮的位置:

class Button:
    def __init__(self, rect_x, rect_y, rect_width, rect_height, text):
        self.rect_x = rect_x
        self.rect_y = rect_y
        self.rect_width = rect_width
        self.rect_height = rect_height   
        self.text = text   
        self.font = pygame.freetype.SysFont('Arial', 25)

    def draw(self):
        pygame.draw.rect(screen, (200, 200, 200), 
            (self.rect_x, self.rect_y, self.rect_width, self.rect_height))     
        self.font.render_to(screen, (self.rect_x + 42, self.rect_y + 25), self.text, bg)