Menu
CoddyTech

Open a Window

Lesson 1 of 40 in Coddy's Make Games with Pygame course.

Pygame is a Python library for making 2D games. A pygame game opens a window and redraws it many times a second. Each picture is a frame.

The code in the editor is the smallest pygame program that keeps a window open:

pygame.init()
screen = pygame.display.set_mode((400, 300))

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

    pygame.display.flip()

pygame.init() starts pygame. pygame.display.set_mode((400, 300)) opens a window 400 pixels wide and 300 tall, and returns the surface you draw on.

The while running: loop is the game loop. One pass of it makes one frame. pygame.event.get() hands you what happened since the last frame, such as a key press or a click on the window's close button, which arrives as pygame.QUIT. pygame.display.flip() shows the finished frame.

pygame.display.set_caption("My Game") sets the title at the top of the window. Your games run in the browser here, and the same code opens a real window on your computer.

challenge icon

Challenge

Easy

Make this window ready for your first game:

  1. Make it 480 pixels wide and 360 tall.
  2. Set its title to Move the Square with pygame.display.set_caption(), after the set_mode line.

Try it yourself

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 300))

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

    pygame.display.flip()

pygame.quit()
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Make Games with Pygame

Practice on your own: Pygame playground