pygame.error:视频系统未初始化,python.display.update错误

时间:2019-05-29 04:47:59

标签: python pygame

我有一个简单的pygame文本打印代码。 当它运行时,它将打开pygame窗口,然后崩溃。

我已经多次检查是否没有错过任何东西,但找不到任何不正确的东西。

代码


import pygame
from pygame.locals import *

def draw():
    pygame.init();
    screen=pygame.display.set_mode((1600, 900))
    pygame.display.set_caption("Damn")
    font = pygame.font.Font('freesansbold.ttf', 32)
    text = font.render('0', True, (0, 0, 0))
    textRect=text.get_rect()
    textRect.center=(800, 450)


    while True:
        screen.fill((255, 255, 255))
        screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type -- pygame.QUIT:
                pygame.quit()
            pygame.display.update()

if __name__=="__main__":
    draw();

错误


Traceback (most recent call last):
  File "C:/Users/Ienovo/PycharmProjects/untitled/Base.py", line 23, in <module>
    draw();
  File "C:/Users/Ienovo/PycharmProjects/untitled/Base.py", line 20, in draw
    pygame.display.update()
pygame.error: video system not initialized


预期结果应该是在中间打印为“ 0”。

1 个答案:

答案 0 :(得分:1)

条件:

if event.type -- pygame.QUIT:
    pygame.quit()

始终评估True

必须为:

if event.type == pygame.QUIT:
    pygame.quit()

相等运算符为==。参见Operators
event.type -- pygame.QUIT的意思是event.type减去-pygame.QUIT

pygame.quit()未初始化所有pygame模块,并导致代码在尝试访问pygame模块的下一条指令时崩溃。


对显示pygame.display.update()的更新应该在主循环而不是事件循环中进行一次:

def draw():

    # [...]   

    run = True
    while True:
        screen.fill((255, 255, 255))
        screen.blit(text, textRect)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        # <---
        pygame.display.update()

    pygame.quit()
相关问题