视频系统未初始化

时间:2020-04-15 04:00:28

标签: python pygame

运行以下代码时,出现错误。其他大多数类似的帖子都谈论pygame.quit() sys.exit(),但仍然看到错误

import pygame, sys, math
pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode((width, height))
ball = pygame.image.load("GolfBall.png").convert_alpha()
ball_rect= ball.get_rect()
is_playing= True
while is_playing:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_playing= False
        screen.fill((0,0,0))
        screen.blit(ball, ball_rect)
        pygame.display.flip()
        pygame.time.wait(20)
    pygame.quit()
sys.exit()

错误是

Traceback (most recent call last):
  File "C:/Users/.............................", line 10, in <module>
    for event in pygame.event.get():
pygame.error: video system not initialized

2 个答案:

答案 0 :(得分:0)

pygame.quit()应该退出循环:

import pygame, sys, math
pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode((width, height))
ball = pygame.image.load("GolfBall.png").convert_alpha()
ball_rect= ball.get_rect()
is_playing= True
while is_playing:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_playing= False
        screen.fill((0,0,0))
        screen.blit(ball, ball_rect)
        pygame.display.flip()
        pygame.time.wait(20)
pygame.quit()
sys.exit()

否则,在循环的第一次迭代之后,pygame.quit()将被调用,而在第二次迭代中将发生错误。

答案 1 :(得分:0)

您必须关心Indentation

虽然pygame.quit()必须在主应用程序循环之后完成(如另一个答案和注释中所述),但绘制场景和更新显示必须在主应用程序循环中完成,而不是事件循环:

import pygame, sys, math
pygame.init()
size = width, height = 600, 400
screen = pygame.display.set_mode((width, height))
ball = pygame.image.load("GolfBall.png").convert_alpha()
ball_rect= ball.get_rect()

# application loop
is_playing= True
while is_playing:

    # event loop
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            is_playing= False

    #<--| INDENTATION

    # draw the scene
    screen.fill((0,0,0))
    screen.blit(ball, ball_rect)
    pygame.display.flip()

    pygame.time.wait(20) 

#<--| INDENTATION

# quit pygame   
pygame.quit()
sys.exit()

注意,事件循环对每个事件执行一次,但是应用程序循环对每个帧执行一次。