我试图在屏幕顶部显示平台游戏的得分,但是每次运行它时,都会出现此错误:“文本必须是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线有关,但我不知道问题出在哪里。
render
的第一个参数必须是字符串,似乎您尝试传递数字。
从docs:
文本只能是一行:不显示换行符。空字符('x00')引发TypeError。 Unicode和char(字节)字符串都可以接受。
首先使用str
函数将值转换为字符串:
font.render(str(text), True, colour)