“Text has zero width” error after reinitializing P

2020-03-08 06:42发布

I have a project in Pygame 1.9.2 where I reinitialize the display multiple times, and draw text to the display surface. It works fine until I close the Pygame display and re-initialize it again.

It follows a structure like this:

from pygame import *
init() # this is pygame.init()
running = True
while running:
    display.set_mode((800,600))
    visible = True
    textFont = font.SysFont("Comic Sans MS", 12)
    while visible:
        for evt in event.get():
            if evt.type == QUIT:
                visible = False
            if evt.type == KEYDOWN:
                if evt.key == K_ESCAPE:
                    visible = running = False
        textPic = textFont.render("Hello world!", True, (255,255,255))
        display.get_surface().blit(textPic, (0,0))
        display.flip()
    quit()

This program works until the display is closed for the first time and then reinitialized, after which I receive the following error when trying to use textFont.render:

pygame.error: Text has zero width

I'm tearing my hair out trying to figure out what's wrong... I know that "Hello world!" has a width greater than zero. How do I fix this problem?

标签: python pygame
2条回答
放荡不羁爱自由
2楼-- · 2020-03-08 07:12

The problem is that pygame.quit() was called before the program was finished. This causes every Pygame module (e.g. pygame.font) to be uninitialized.

Instead of relying on pygame.quit to close the Pygame display, use pygame.display.quit at the end of every while running loop. Then put pygame.quit at the very end of the script to unload the rest of the modules after they're done being used.

(Calling pygame.init() again before rendering text won't fix this issue either, because it causes the Pygame display to stop responding. (This might be a bug with Pygame 1.9.2)

查看更多
够拽才男人
3楼-- · 2020-03-08 07:12

I found a solution that worked for me: just delete the font element before calling pygame.display.quit(), ie just del font every time you're done using it.

The font element is the one you created using the command:

font.SysFont("Comic Sans MS", 12)

but that I personally create using pygame.font.Font(None, font_size)

查看更多
登录 后发表回答