'pygame.key.get_pressed() pygame.error: video system not initialized

while True:
    screen.fill(white)
    cooldown += 1

    # --- Event Processing
    pygame.draw.rect(screen, black, (0, 500, 1000, 200))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

        elif event.type == pygame.MOUSEBUTTONDOWN:
            # Fire a bullet if the user clicks the mouse button
            bullet = Bullet()
            # Set the bullet so it is where the player is
            bullet.rect.x = player.rect.x + 40
            bullet.rect.y = player.rect.y + 10
            # Add the bullet to the lists
            if cooldown > 49:
                all_sprites_list.add(bullet)
                bullet_list.add(bullet)
                cooldown = 0

    keys = pygame.key.get_pressed()

    def horzMoveAmt():
        ''' Amount of horizontal movement based on left/right arrow keys, moving the player events '''
        return (keys[K_d] - keys[K_a]) * HORZ_MOVE_INCREMENT

line 248, in game_loop keys = pygame.key.get_pressed() pygame.error: video system not initialized My game works but this message appears when I close the game window. Why?



Solution 1:[1]

Looks like you are calling pygame.quit() as you are quitting the game, but you are not at the end of your program.

To solve your problem you can use the running variable for your mainloop and instead set that to false. At the end of your program you then call pygame.quit(). As such:

pygame.init()

while running:
    if event.type == pygame.QUIT:
        running = False
    gameCode

pygame.quit()

This change means that you are not trying to access a part of pygame after you have quit it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1