Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 41 ยท Getting Started

Import and Initialize Pygame

Learn what pygame.init() does, how to initialize only some modules, read its success and failure counts, check get_init() and shut down cleanly with pygame.quit().

Every Pygame program begins with two things: importing the library and initializing it. The import loads Python code; the initialization starts the underlying SDL subsystems (video, audio, timers, joysticks). If you forget to initialize, some features raise errors such as pygame.error: video system not initialized. This lesson explains exactly what init() does and how to shut down cleanly.

Importing

The standard form is:

Python
import pygame

Avoid from pygame import *. It dumps hundreds of names, including constants like K_a, into your namespace and hides where things come from. A common middle ground is from pygame.locals import * for just the constants, but plain pygame.K_a style is clearer and is what this course uses.

Importing alone is cheap. Many pure-computation parts work right after the import without any initialization: pygame.Rect, pygame.Surface, pygame.Color, pygame.math.Vector2, pygame.draw and pygame.transform.

pygame.init()

pygame.init() initializes all the modules that need it, in one call:

Python
import pygame

successes, failures = pygame.init()
print(f"{successes} modules started, {failures} failed")

It returns a tuple (numpass, numfail): how many modules initialized and how many did not. A failure is not an exception. For example, on a machine without a sound card the mixer can fail while the rest works, so the game can continue without sound. Many tutorials ignore the return value, but checking it helps debugging.

Note: pygame.init() needs a real machine with a display. The browser runner on this site is headless, so the lessons here call the small init() of just the modules they use, such as pygame.font.init().

Initializing only what you need

pygame.init() is convenient, but each module has its own init() and quit(). Initializing only the ones you use starts the program faster and avoids touching hardware you do not need (for example the audio device in a silent tool):

Python
import pygame

pygame.display.init()
pygame.font.init()
pygame.mixer.init()      # may fail on machines without audio

Each module also has get_init() to ask whether it is ready:

Python
print(pygame.display.get_init())   # True or False
print(pygame.font.get_init())
print(pygame.mixer.get_init())     # None if not initialized, else (frequency, format, channels)

Note that pygame.mixer.get_init() returns a tuple describing the audio format, not a plain True.

Try it: initialize one module

Fonts are a module you can initialize anywhere. This example starts pygame.font on its own, checks it and uses it.

Python Initialize a single module

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.

Using a module that is not initialized raises pygame.error. Try deleting the pygame.font.init() line to see it.

Try it: handle an uninitialized module

Because errors such as "not initialized" are ordinary exceptions, you can catch them. This is useful when a feature is optional.

Python pygame.error when a module is not ready

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.

pygame.error is Pygame's own exception class. It covers every problem that comes from the SDL layer: missing files, no video device, bad audio format.

pygame.quit()

At the end of the program call:

Python
pygame.quit()

It shuts down every initialized module and releases the window, the audio device and other resources. Calling it twice is harmless. After pygame.quit() you must not call display or mixer functions; doing so raises pygame.error.

A reliable pattern is to wrap the program so quit always runs, even after a crash:

Python
import pygame

def main():
    pygame.init()
    try:
        run_game()
    finally:
        pygame.quit()

if __name__ == "__main__":
    main()

The if __name__ == "__main__": guard means the game starts only when you run the file directly, not when something imports it. You will need that when you split a game across files in the architecture chapter.

Mixer pre-initialization

Sound has one special rule. The audio format (frequency, size, channels, buffer) is chosen when the mixer starts, so to change it you must configure it before pygame.init():

Python
import pygame

pygame.mixer.pre_init(44100, -16, 2, 512)   # frequency, size, channels, buffer
pygame.init()

A smaller buffer reduces the delay between pressing a key and hearing the sound; too small a buffer can crackle. Sound is covered in depth later in the course.

Common mistakes

  • Using Pygame before init(): you get pygame.error: ... not initialized.
  • Forgetting pygame.quit(): usually harmless at exit, but it matters in long-lived programs and tests.
  • Calling pygame.init() inside the loop: it belongs once, at the start.
  • from pygame import *: pollutes the namespace; prefer import pygame.
  • Ignoring the failure count when sound or joysticks suddenly stop working: print pygame.init()'s result to see it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does pygame.init() return?

    It returns (numpass, numfail). A failed module does not raise an exception.
  2. 2. Which error do you get when you use a module that was not initialized?

    Pygame raises its own pygame.error, for example "video system not initialized".
  3. 3. When must pygame.mixer.pre_init(...) be called?

    The audio format is fixed when the mixer starts, so you configure it before initialization.
  4. 4. Why call pygame.quit() in a finally block?

    A finally block always runs, so resources are released after normal exit and after exceptions.

Summary

  • Use import pygame; avoid from pygame import *.
  • pygame.init() starts all modules and returns (numpass, numfail).
  • Each module has init(), quit() and get_init() for finer control.
  • pygame.error is the exception for SDL-level problems.
  • Call pygame.quit() at the end, ideally in a finally block.
  • Configure the mixer with pre_init() before init().

Next: Your First Pygame Window