Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
633 views
in Technique[技术] by (71.8m points)

python - How to display some text in pygame?

I am currently on a pygame project and wanted to display some text. I have done this before in another program and it works just fine but when I write the exact same thing in this project, it gives this error :

Traceback (most recent call last):
  File "C:UsersFazelifarDesktopDot Game.py", line 197, in <module>
    myfont = pygame.font.SysFont(None, 15)
  File "C:UsersFazelifarAppDataLocalProgramsPythonPython37-32libsite-packagespygamesysfont.py", line 362, in SysFont
    return constructor(fontname, size, set_bold, set_italic)
  File "C:UsersFazelifarAppDataLocalProgramsPythonPython37-32libsite-packagespygamesysfont.py", line 285, in font_constructor
    font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized

and here is my code :

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

plz help I am stuck

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

pygame has to be initialized, before a instance of Font respectively SysFont can be created. More accurate, the pygame.font modul has to be initialized.

pygame.font.init()

But note, pygame.init() would initialize the pygame.font module, too. pygame.init() initialize all imported pygame modules.

The name of the instance of pygame.font.SysFont is myfont, rather than lala. So it has to be:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...