Getting started with Pygame
Install Pygame, open a window and understand the three-part loop that every Pygame program is built on.
On this page
What you'll learn
- How to install Pygame and check that it works
- How to open a window and keep it open
- Why every Pygame program has an event loop
- How to draw a shape and a line of text
Prerequisites: Python 3 installed, and basic Python: variables, if, while and for loops.
Step 1: Install Pygame#
Open a terminal (Command Prompt or PowerShell on Windows, Terminal on macOS and Linux) and run:
python -m pip install pygameOn macOS and Linux you may need python3 instead of python. Using python -m pip instead of plain pip makes sure the package goes into the same Python you will run your game with, which avoids the most common beginner problem. If you prefer the community edition, run python -m pip install pygame-ce instead. Both use import pygame and everything in these tutorials works with either. Which one should I pick?
Check the installation with Pygame's built-in example game:
python -m pygame.examples.aliensA window with a small shooting game should open. If you see No module named pygame instead, follow the fix for that error. Detailed, operating-system-specific steps are in the installation guides.
Step 2: Open a window#
Create a file called hello_window.py and type this in:
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("My first Pygame window")
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((30, 60, 120))
pygame.display.flip()
pygame.quit()Run it with python hello_window.py. A dark blue window appears and stays open until you click its close button.
Here is what each part does:
pygame.init()starts all of Pygame's modules (display, fonts, sound and so on). Call it once, near the top.pygame.display.set_mode((640, 480))opens a window 640 pixels wide and 480 pixels tall and returns a Surface, an image you can draw on. We call itscreen.- The
while running:loop is the game loop. It runs over and over until we setrunningtoFalse. pygame.event.get()returns everything that happened since the last check: key presses, mouse clicks, and the window's close button, which arrives as apygame.QUITevent.screen.fill(...)paints the whole window one colour. Colours are(red, green, blue)tuples with values from 0 to 255.pygame.display.flip()shows what you have drawn. Until you call it, your drawing happens off-screen.pygame.quit()shuts Pygame down cleanly after the loop ends.
If you never call pygame.event.get(), your operating system decides the program has frozen. The window stops responding and may show "Not Responding". Even a program with no controls needs the event loop. See window not responding.
Step 3: Add a clock, a shape and text#
The first program redraws as fast as your computer allows, which wastes power. A Clock limits the frame rate. Let's also draw something:
import pygame
WIDTH, HEIGHT = 640, 480
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Hello, Pygame")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 48) # None = Pygame's built-in font
running = True
while running:
# 1. Handle events
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# 2. Update the game (nothing moves yet)
# 3. Draw the frame
screen.fill("cornflowerblue")
pygame.draw.circle(screen, "gold", (WIDTH // 2, HEIGHT // 2 - 40), 50)
text = font.render("Hello, Pygame!", True, "white")
screen.blit(text, text.get_rect(center=(WIDTH // 2, HEIGHT // 2 + 60)))
pygame.display.flip()
clock.tick(60) # at most 60 frames per second
pygame.quit()
New pieces:
clock.tick(60)pauses just long enough to keep the loop at no more than 60 frames per second.- Colour names such as
"cornflowerblue"and"gold"work anywhere Pygame expects a colour, and so do RGB tuples. pygame.draw.circle(screen, color, center, radius)draws a filled circle. The drawing shapes tutorial covers the rest ofpygame.draw.- Text is a two-step process:
font.render(...)turns a string into a new Surface, andscreen.blit(...)copies that Surface onto the screen.text.get_rect(center=...)gives a rectangle positioned so the text is centred.
How coordinates work#
Pygame measures positions in pixels from the top-left corner of the window. (0, 0) is the top-left, x grows to the right and y grows downward, the opposite of a maths graph. In a 640 × 480 window the bottom-right pixel is (639, 479). The coordinate visualizer lets you explore this with your mouse.
Common mistakes#
- Drawing after
flip(): anything drawn afterpygame.display.flip()only appears in the next frame. Draw first, flip last. - Forgetting
fill(): without clearing the screen each frame, moving objects leave trails. - Naming your file
pygame.py: Python then imports your file instead of the library and you get confusingAttributeErrors. Rename it and delete anypygame.pycor__pycache__folder next to it. - Calling
pygame.quit()inside the loop: that closes Pygame while the loop still tries to draw, causingpygame.error: video system not initialized.
Practice exercises#
- Change the window to 800 × 600 and the background to your favourite colour.
- Put the text at the bottom-left corner. Hint:
text.get_rect(bottomleft=(10, 590)). - Change the window title with
pygame.display.set_caption(). - Draw three circles in different colours in a row.
Next steps#
You now have the skeleton of every Pygame program. The next lesson, the game loop, explains frame rates and how to move things smoothly. You can also try these programs without installing anything in Pygame Online.