退出 pygame 窗口后出现 pygame 错误

问题描述

我想了解如何在 pygame 中显示字体。但是我收到一条错误消息,说 pygame.error: Library not initialized

在我按下十字按钮或退出我的 pygame 窗口后会发生此错误

谁能告诉我为什么会发生这个错误,我该如何解决

import pygame
from pygame.locals import *
import sys
from win32api import GetSystemMetrics
pygame.init()
WIDTH = GetSystemMetrics(0)
HEIGHT = GetSystemMetrics(1)-64
WIDTH_HEIGHT = (WIDTH,HEIGHT)

WINDOW = pygame.display.set_mode(WIDTH_HEIGHT)
pygame.init()
font = pygame.font.Font('freesansbold.ttf',32)
text = ""

running = True

while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            running = False
    text = font.render('Hi',True,(255,255,255))
    WINDOW.blit(text,(0,0))
    pygame.display.update()

解决方法

这是一种退出方式(刚完成程序):

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
            
pygame.quit()

这是另一种方式(更有力一点):

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()