如何解决pygame-将文本添加到rect的类实例
我正在尝试将文本添加到rect的类实例中。
我可以通过在类之外设置“ 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,'One')
button2 = Button(10,70,'Two')
button3 = Button(10,130,'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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。