PySDL2

0.9.17 · active · verified Fri Apr 17

PySDL2 provides comprehensive Python bindings for the SDL2 (Simple DirectMedia Layer) C library, along with its various extensions (SDL_image, SDL_mixer, SDL_ttf, SDL_gfx). It allows Python developers to create cross-platform multimedia applications, games, and graphical user interfaces. The current version is 0.9.17, with releases typically tied to updates in the underlying SDL2 library, though the pace has slowed as focus shifts towards SDL3 development.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart initializes SDL2 using `sdl2.ext`, creates a basic window, sets up a software renderer, and implements a simple event loop to handle closing the window. It demonstrates the high-level `sdl2.ext` API for common operations. Remember to install native SDL2 libraries on your system before running this code.

import sdl2
import sdl2.ext

RESOURCES = sdl2.ext.Resources(__file__, 'resources')

def run():
    sdl2.ext.init()

    window = sdl2.ext.Window("My PySDL2 Window", size=(800, 600))
    window.show()

    # Create a software renderer for the window
    # Note: For hardware acceleration, you'd typically use sdl2.render.create_renderer
    # and potentially integrate with OpenGL/Vulkan via PyOpenGL.
    renderer = sdl2.ext.Renderer(window)

    running = True
    while running:
        events = sdl2.ext.get_events()
        for event in events:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
        
        # Clear the window to black
        renderer.clear(sdl2.ext.Color(0, 0, 0))
        # You can add drawing commands here
        # renderer.draw_rect(..., sdl2.ext.Color(255, 0, 0))
        
        renderer.present()
        window.refresh()

    sdl2.ext.quit()
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(run())

view raw JSON →