why is my pygame widow only staying open for one second before it closes?

Viewed 256

I am currently following a beginner pygame tutorial on YouTube here but even though I copied the code exactly from the tutorial my pygame window only stays open for about a second and then closes.

note: someone asked this question about three years ago here but it didn't fix my problem. my code is below

import pygame
pygame.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')

1 Answers

Your script is ending and so pygame closes everything.

You have to create a loop in order for your game to continue running, with a condition to exit the loop.

You also need to initialize the display with pygame.display.init()

import pygame
pygame.init()
pygame.display.init()

win = pygame.display.set_mode((500, 500))
pygame.display.set_caption('hello world')

clock = pygame.time.Clock()
FPS = 60  # Frames per second.

# Some shortcuts for colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)

# For example, display a white rect
rect = pygame.Rect((0, 0), (32, 32))
image = pygame.Surface((32, 32))
image.fill(WHITE)

# Game loop
while True:
    # Ensure game runs at a constant speed
    clock.tick(FPS)

    # 1. Handle events
    for event in pygame.event.get():
        # User pressed the close button ?
        if event.type == pygame.QUIT:
            quit()
            # Close the program. Other methods like 'raise SystemExit' or 'sys.exit()'.
            # Calling 'pygame.quit()' won't close the program! It will just uninitialize the modules.

    # 2. Put updates to the game logic here

    # 3. Render
    win.fill(BLACK)  # first clear the screen
    win.blit(image, rect)  # draw whatever you need
    pygame.display.flip()  # copy to the screen
Related