Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 41 ยท Getting Started

Your First Pygame Window

Create your first Pygame window step by step, set its size and background color, run a minimal loop that closes on QUIT, and see what each line does.

Time to put a window on the screen. A working Pygame program needs only about ten lines, and each of them has a clear job. This lesson builds the minimal program one piece at a time, explains the common beginner mistake (a window that flashes and disappears) and shows how to test the loop logic without a display.

The minimal program

Python
import pygame

pygame.init()

screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("My First Window")

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((30, 30, 46))
    pygame.display.flip()

pygame.quit()

Save it as window.py and run python window.py. A dark 800 by 600 window appears and stays until you close it. This is real window code, so it is read-only here. Let us go through it.

1. Initialize

pygame.init() starts the modules, as explained in Import and Initialize.

2. Create the window

pygame.display.set_mode((800, 600)) creates the window and returns a Surface that represents everything inside it. We call it screen by habit. The argument is a tuple (width, height) in pixels. A common mistake is writing set_mode(800, 600) without the inner parentheses; Pygame needs one tuple.

set_caption("My First Window") sets the title shown in the title bar.

3. The loop and events

while running: repeats for the life of the game. Inside it pygame.event.get() returns the list of everything that happened since the last call: key presses, mouse clicks, window moves. When the player clicks the close button, a pygame.QUIT event arrives. We react by setting running = False, which ends the loop.

Warning: If you do not read events, the operating system thinks your program is frozen. The window shows "Not responding" and the close button does nothing. Always call pygame.event.get() (or pygame.event.pump()) every frame.

4. Draw and show

screen.fill((30, 30, 46)) paints the whole screen with a color (red, green, blue). Drawing happens on a hidden buffer. pygame.display.flip() swaps the finished buffer onto the monitor. Without it, you would see nothing change. There is also pygame.display.update(), which can refresh only parts of the screen; for now flip() is the simplest choice. See The Window and Display.

5. Quit

After the loop ends, pygame.quit() releases resources.

Why my window flashes and disappears

If you leave out the loop, the program draws once, reaches the end and exits at once. The loop is what keeps the window alive. Also check that the loop is not accidentally inside the if and that running is not set to False before the first frame.

Try it: the loop without a window

We cannot open a window here, but we can test the logic. Pygame's Event objects can be created without a display, so this stand-in feeds the loop a scripted list of frames, each containing the events that "happened". It stops on QUIT, just like the real program.

Python Stand-in: a loop that stops on QUIT

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The code inside the for event loop is exactly what you would write in a real game. Only the source of the events (a list instead of the operating system) differs.

Try it: the window surface

set_mode returns a plain Surface. We can make an identical off-screen surface, fill it and inspect it. This is how you can reason about colors and sizes before you ever open a window.

Python The window is just a Surface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reading a pixel outside the surface raises an IndexError. The last valid pixel is (width - 1, height - 1) because counting starts at 0.

A reusable template

Most of your programs will start from this slightly improved skeleton. It uses a Clock to hold 60 FPS (explained in The Game Loop) and a main() function:

Python
import pygame

WIDTH, HEIGHT = 800, 600
FPS = 60
BACKGROUND = (30, 30, 46)


def main():
    pygame.init()
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Game Template")
    clock = pygame.time.Clock()

    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False

        screen.fill(BACKGROUND)
        # ... draw your game here ...
        pygame.display.flip()
        clock.tick(FPS)

    pygame.quit()


if __name__ == "__main__":
    main()

Constants in capital letters (WIDTH, FPS) make the game easy to tune. Pressing Escape also quits, which is handy while developing.

Common mistakes

  • set_mode(800, 600) instead of set_mode((800, 600)).
  • Missing pygame.display.flip(): the window stays blank.
  • Never calling pygame.event.get(): the window freezes.
  • Creating the window inside the loop: it would be recreated every frame.
  • Calling pygame.quit() inside the loop, then drawing: pygame.error: display Surface quit.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does pygame.display.set_mode((800, 600)) return?

    It returns the display Surface, which you draw on and then show with flip() or update().
  2. 2. Your window opens and immediately closes. What is the most likely cause?

    Without a loop the program ends right after drawing once. The loop keeps it alive until QUIT.
  3. 3. What happens if you never call pygame.event.get()?

    The operating system sees the app as not responding because its events are never processed.
  4. 4. Which pixel is the last valid one on a 800 by 600 surface?

    Coordinates start at 0, so the last pixel is at (width - 1, height - 1).
  5. 5. What does pygame.display.flip() do?

    Drawing goes into a hidden buffer; flip() makes the finished frame visible.

Summary

  • A minimal program: init, set_mode, a loop that reads events, fill, flip, quit.
  • set_mode takes a single (width, height) tuple and returns the screen Surface.
  • You must process events every frame, or the window freezes.
  • Nothing appears until pygame.display.flip() or update().
  • Test loop logic without a window by feeding scripted Event objects.

Next: The Window and Display