hmmmm
hmmmm

Reputation: 23

Why does my pygame window close instantly?

I am on Ubuntu and I want to use PyGame for a beginner's project. But when I run the program for the window, it only opens briefly then closes back out. How do I fix this?

import pygame
pygame.init()

window = pygame.display.set_mode((700,700))
pygame.display.set_caption("First Game")

Upvotes: 1

Views: 104

Answers (1)

Kingsley
Kingsley

Reputation: 14906

Your PyGame program needs to at least service the event loop. The program is opening the window, but then doing nothing, so it just closes again.

Try something like this:

import pygame

WINDOW_WIDTH  = 700
WINDOW_HEIGHT = 700
SKY_BLUE = (161, 255, 254)

### Open the PyGame Wdinow
pygame.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption("First Game")

### make a clock for later.
clock = pygame.time.Clock()

### Main Loop
done = False
while not done:
    # Handle Window Events, etc.
    for event in pygame.event.get():
        if ( event.type == pygame.QUIT ):
            done = True

    # Handle Movement keys
    keys = pygame.key.get_pressed()
    if ( keys[pygame.K_UP] ):
        print("up")
    elif ( keys[pygame.K_DOWN] ):
        print("down")
    elif ( keys[pygame.K_LEFT] ):
        print("left")
    elif ( keys[pygame.K_RIGHT] ):
        print("right")


    # Update the window
    window.fill( SKY_BLUE )

    # Flush all updates out to the window
    pygame.display.flip()

    # Clamp frame-rate to 60 FPS
    clock.tick_busy_loop(60)

pygame.quit()

This opens a minimal window, handles the window-close event, paints the background blue. It will register key-presses for arrow keys, but other than that does very little.

Upvotes: 1

Related Questions