【发布时间】:2020-09-29 12:25:36
【问题描述】:
我正在尝试将文本添加到矩形的类实例中。
我已经能够通过在类之外设置“font”变量并将所需的文本放在绘图函数中的“font.render_to”中来做到这一点,但这意味着所有按钮的文本都将与它相同在类中设置。
我想为类实例(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()
【问题讨论】:
-
或许你应该将
font参数重命名为text;那么你应该清楚你做错了什么(尝试对字体对象和文本值使用属性font)。 -
仔细看看构造函数的最后一行。你正在做
self.font = 'One'.pygame.freetype.SysFont('Arial', 25),它是说 str (在本例中为“One”)没有 pygame 属性。正如@sloth 建议的那样,您应该使用变量名text和self.text来存储字符串,并使用self.font来存储字体。您还必须在draw函数中更改它。
标签: python python-3.x text pygame rect