1
votes

I have a simple pygame text print code. When it is run, it opens the pygame window and then crashes.

I have checked multiple times if i haven't missed anything, but I can't find anything which is incorrect.

The code


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();

The error


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


The expected result should be the '0' being print at the center.

1

1 Answers

1
votes

The condition:

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

evaluates always True.

It has to be:

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

The equality operator is ==. See Operators.
The meaning of event.type -- pygame.QUIT is event.type minus -pygame.QUIT.

pygame.quit() uninitializes all pygame modules and causes the code to crashes at the next instruction which tries to access a pygame module.


The update of the display pygame.display.update() should be done once in the scope of the main loop rather than the event loop:

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()