【发布时间】:2019-12-04 11:51:41
【问题描述】:
我试图在屏幕顶部显示平台游戏的分数,但每次运行时都会出现以下错误: “文本必须是 Unicode 或字节” 我已经在网站上查看过,代码看起来和我写的完全一样,但我仍然遇到同样的错误。到目前为止,这是我的代码:
def __init__(self):
#this has all the things needed to initialise the game but the only relevant one to my problem is this line
self.font_name = pygame.font.match_font(FONT_NAME)
def draw(self):
self.screen.fill(BLACK)
self.all_sprites.draw(self.screen)
self.draw_text(self.score, 22, WHITE, WIDTH / 2, 15)
pygame.display.flip()
def draw_text(self, text, size, colour, x, y):
font = pygame.font.Font(self.font_name, size)
text_surface = font.render(text, True, colour)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
self.screen.blit(text_surface, text_rect)
所有大写的东西都在另一个我称为设置的文件中被赋予了值,然后导入到这个文件中。
问题似乎与 text_surface 线有关,但我不知道问题是什么。
【问题讨论】:
-
你确定
text实际上是一个字符串吗?如果是数字,请改用font.render(strr(text), True, colour)。 -
显然是
str,而不是strr -
@sloth 是的!非常感谢您对它进行排序
-
您好!此外,如果您希望在字符串中包含换行符,请使用 ptext
标签: python unicode pygame render draw