首页 > 解决方案 > 如何在pygame中显示一些文本?

问题描述

我目前在一个 pygame 项目中,想显示一些文本。我以前在另一个程序中做过这个,它工作得很好,但是当我在这个项目中写完全相同的东西时,它给出了这个错误:

Traceback (most recent call last):
  File "C:\Users\Fazelifar\Desktop\Dot Game.py", line 197, in <module>
    myfont = pygame.font.SysFont(None, 15)
  File "C:\Users\Fazelifar\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sysfont.py", line 362, in SysFont
    return constructor(fontname, size, set_bold, set_italic)
  File "C:\Users\Fazelifar\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sysfont.py", line 285, in font_constructor
    font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized

这是我的代码:

myfont = pygame.font.SysFont(None, 15)
def txt_display (txt , color , x , y):
   txt = lala.render(txt , True , black)
   main.blit(txt , (x , y))

请帮助我卡住了

标签: pythonfontspygame

解决方案


pygame 必须被初始化,然后才能创建 Font 和 SysFont 的实例。更准确地说,pygame.font必须初始化模块。

pygame.font.init()

但请注意,pygame.init()也会初始化pygame.font模块。pygame.init()初始化所有导入的 pygame 模块。

实例的名称pygame.font.SysFontmyfont,而不是lala。所以它必须是:

txt = lala.render(txt , True , black)

txt = myfont.render(txt , True , black)

推荐阅读