这个错误是什么意思?Pygame错误:字体未初始化。

6

我目前正在制作一款小游戏,但是它显示了一个奇怪的错误信息。具体来说:

'Pygame Error': Font Not Initialized

这是什么意思?

这是我的代码:

import pygame, random, sys, os, time
import sys
from pygame.locals import *
WINDOWWIDTH = 800
WINDOWHEIGHT = 600
levens = 3
dead = False
Mousevisible = False

def terminate():
    pygame.quit()
    sys.exit()

def waitForPlayerToPressKey():
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                terminate()
            if event.type == KEYDOWN:
                if event.key == K_ESCAPE: #escape quits
                    terminate()
                return

def drawText(text, font, surface, x, y):
    textobj = font.render(text, 1, TEXTCOLOR)
    textrect = textobj.get_rect()
    textrect.topleft = (x, y)
    surface.blit(textobj, textrect)
#fonts
font = pygame.font.SysFont(None, 30)

#def gameover():
    #if dead == True:
        #pygame.quit

# set up pygame, the window, and the mouse cursor
pygame.init()
mainClock = pygame.time.Clock()
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.display.set_caption('hit the blocks')
pygame.mouse.set_visible(Mousevisible)

# "Start" screen
drawText('Press any key to start the game.', font, windowSurface, (WINDOWWIDTH / 3) - 30, (WINDOWHEIGHT / 3))
drawText('And Enjoy', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3)+30)
pygame.display.update()
waitForPlayerToPressKey()
zero=0
    

以下是错误信息:

Traceback (most recent call last):
  File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\schietspel.py", line 30, in <module>
    font = pygame.font.SysFont(None, 30)
  File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sysfont.py", line 320, in SysFont
    return constructor(fontname, size, set_bold, set_italic)
  File "C:\Users\flori\AppData\Local\Programs\Python\Python37-32\lib\site-packages\pygame\sysfont.py", line 243, in font_constructor
    font = pygame.font.Font(fontpath, size)
pygame.error: font not initialized

1
如果您不提供代码(或相关部分),我们无法为您提供帮助。 - glhr
1
始终在问题中放置完整的错误消息(完整跟踪),而不是屏幕截图。有其他有用的信息,它应该显示您在哪行代码中遇到了问题。 - furas
展示你的代码 - 我们无法读取你的思想。 - furas
在开始之前,你应该使用 Google 查找关于 'Pygame Error': Font Not Initialized 的更多信息。也许已经有人遇到过这个问题并解决了它。这样你就可以在几个小时前就得到答案了。 - furas
3个回答

10
问题在于你在初始化游戏之前设置了字体。为了解决这个问题,请将 font = pygame.font.SysFont(None, 30) 放在 pygame.init() 后面。
另外,为了使你的代码正常运行,你需要定义 TEXTCOLOR。它应该是一个包含RGB值的元组,例如:TEXTCOLOR = (255, 255, 255) 表示白色(你可以将其放在顶部与 WINDOWHEIGHT 一起)。

0
在我的情况下,在pygame.font.Font()之前添加pygame.init()可以解决这个问题。

0

我认为你需要初始化pygame.font。

from pygame.locals import *之后尝试使用pygame.font.init()


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接