Pure Python wrapper around SDL2 libraries for cross-platform multimedia development
npx @tessl/cli install tessl/pypi-pysdl2@0.9.0PySDL2 is a pure Python wrapper around the SDL2, SDL2_mixer, SDL2_image, SDL2_ttf, and SDL2_gfx libraries. Instead of relying on C code, it uses Python's built-in ctypes module to interface with SDL2, and provides simple Python classes and wrappers for common SDL2 functionality.
pip install PySDL2pip install pysdl2-dll)import sdl2
import sdl2.extModule-level imports:
import sdl2.video
import sdl2.events
import sdl2.render
import sdl2.ext.window
import sdl2.ext.rendererimport sdl2
import sdl2.ext
# Initialize SDL2 extensions
sdl2.ext.init()
# Create a window
window = sdl2.ext.Window("Hello PySDL2", size=(800, 600))
window.show()
# Create a renderer for hardware-accelerated graphics
renderer = sdl2.ext.Renderer(window)
# Main event loop
running = True
while running:
events = sdl2.ext.get_events()
for event in events:
if event.type == sdl2.SDL_QUIT:
running = False
# Clear screen with blue color
renderer.clear((0, 100, 200))
# Present the rendered frame
renderer.present()
# Cleanup
sdl2.ext.quit()PySDL2 provides a two-tier architecture:
sdl2.*): Low-level ctypes wrappers that mirror SDL2's C API exactly, providing direct access to all SDL2 functionality with minimal overheadsdl2.ext.*): High-level Pythonic classes and utilities built on the core bindings, offering simplified interfaces for common tasksThis design allows developers to choose between direct SDL2 control (core) and Python convenience (extensions), often mixing both approaches within the same application.
Window creation, display mode handling, and OpenGL context management. Provides both low-level window control and high-level window classes.
# Core window functions
def SDL_CreateWindow(title: bytes, x: int, y: int, w: int, h: int, flags: int) -> SDL_Window
def SDL_DestroyWindow(window: SDL_Window) -> None
def SDL_ShowWindow(window: SDL_Window) -> None
# Extension window class
class Window:
def __init__(self, title: str, size: tuple[int, int] = (800, 600), position: tuple[int, int] = None, flags: int = 0)
def show(self) -> None
def hide(self) -> NoneComprehensive event system for keyboard, mouse, joystick, and system events. Includes both polling and event-driven approaches.
# Core event functions
def SDL_PollEvent(event: SDL_Event) -> int
def SDL_WaitEvent(event: SDL_Event) -> int
# Extension event utilities
def get_events() -> list[SDL_Event]
def key_pressed(key: int) -> bool
def mouse_clicked() -> boolComplete joystick and game controller support with both raw joystick access and standardized game controller mapping.
# Joystick functions
def SDL_NumJoysticks() -> int
def SDL_JoystickOpen(device_index: int) -> SDL_Joystick
def SDL_JoystickClose(joystick: SDL_Joystick) -> None
def SDL_JoystickNumAxes(joystick: SDL_Joystick) -> int
def SDL_JoystickNumButtons(joystick: SDL_Joystick) -> int
def SDL_JoystickGetAxis(joystick: SDL_Joystick, axis: int) -> int
def SDL_JoystickGetButton(joystick: SDL_Joystick, button: int) -> int
# Game controller functions
def SDL_GameControllerOpen(joystick_index: int) -> SDL_GameController
def SDL_GameControllerClose(gamecontroller: SDL_GameController) -> None
def SDL_GameControllerGetAxis(gamecontroller: SDL_GameController, axis: int) -> int
def SDL_GameControllerGetButton(gamecontroller: SDL_GameController, button: int) -> intJoystick and Game Controller Input
Software and hardware-accelerated rendering with support for textures, primitives, and surface operations.
# Core rendering functions
def SDL_CreateRenderer(window: SDL_Window, index: int, flags: int) -> SDL_Renderer
def SDL_RenderClear(renderer: SDL_Renderer) -> int
def SDL_RenderPresent(renderer: SDL_Renderer) -> None
# Extension renderer class
class Renderer:
def __init__(self, target: Window, index: int = -1, flags: int = 0)
def clear(self, color: tuple[int, int, int] = (0, 0, 0)) -> None
def present(self) -> NoneAudio playback, recording, and mixing capabilities through SDL2_mixer integration.
# Core audio functions
def SDL_OpenAudioDevice(device: bytes, iscapture: int, desired: SDL_AudioSpec, obtained: SDL_AudioSpec, allowed_changes: int) -> int
def SDL_CloseAudioDevice(dev: int) -> None
# Mixer functions
def Mix_OpenAudio(frequency: int, format: int, channels: int, chunksize: int) -> int
def Mix_LoadWAV(file: bytes) -> Mix_Chunk
def Mix_PlayChannel(channel: int, chunk: Mix_Chunk, loops: int) -> intHigh-precision timing functions for animations, frame rate control, and custom timer callbacks.
def SDL_GetTicks() -> int
def SDL_GetTicks64() -> int
def SDL_Delay(ms: int) -> None
def SDL_GetPerformanceCounter() -> int
def SDL_GetPerformanceFrequency() -> int
def SDL_AddTimer(interval: int, callback: SDL_TimerCallback, param: int) -> int
def SDL_RemoveTimer(timer_id: int) -> boolFile I/O abstraction layer supporting files, memory buffers, and custom data sources through SDL_RWops.
def SDL_RWFromFile(file: bytes, mode: bytes) -> SDL_RWops
def SDL_RWFromMem(mem: bytes, size: int) -> SDL_RWops
def SDL_RWFromConstMem(mem: bytes, size: int) -> SDL_RWops
def SDL_RWclose(context: SDL_RWops) -> int
def SDL_RWread(context: SDL_RWops, ptr: bytes, size: int, num: int) -> int
def SDL_RWwrite(context: SDL_RWops, ptr: bytes, size: int, num: int) -> int
def SDL_RWseek(context: SDL_RWops, offset: int, whence: int) -> intSystem integration functions for clipboard access, file system paths, platform detection, and power management.
# Clipboard functions
def SDL_SetClipboardText(text: bytes) -> int
def SDL_GetClipboardText() -> bytes
def SDL_HasClipboardText() -> bool
# File system functions
def SDL_GetBasePath() -> bytes
def SDL_GetPrefPath(org: bytes, app: bytes) -> bytes
# Platform detection
def SDL_GetPlatform() -> bytes
# Power management
def SDL_GetPowerInfo(secs: int, pct: int) -> intSystem Integration and Utilities
High-level sprite management, animation, and rendering systems for 2D games and applications.
class Sprite:
def __init__(self, x: int = 0, y: int = 0)
class SpriteFactory:
def __init__(self, sprite_type: int = TEXTURE, renderer: Renderer = None)
def from_image(self, fname: str) -> Sprite
def from_color(self, color: tuple[int, int, int, int], size: tuple[int, int]) -> Sprite
class SpriteRenderSystem:
def render(self, sprites: list[Sprite]) -> NoneTrueType font loading and text rendering through SDL2_ttf integration.
# TTF functions
def TTF_Init() -> int
def TTF_OpenFont(file: bytes, ptsize: int) -> TTF_Font
def TTF_RenderText_Solid(font: TTF_Font, text: bytes, fg: SDL_Color) -> SDL_Surface
# Extension font classes
class FontTTF:
def __init__(self, font_path: str, size: int)
def render(self, text: str, color: tuple[int, int, int] = (255, 255, 255)) -> SDL_Surface
class FontManager:
def add(self, font_path: str, alias: str = None, size: int = 16) -> None
def get(self, alias: str, size: int = 16) -> FontTTFImage loading, saving, and manipulation through SDL2_image integration.
# Image loading functions
def IMG_Load(file: bytes) -> SDL_Surface
def IMG_LoadTexture(renderer: SDL_Renderer, file: bytes) -> SDL_Texture
# Extension image utilities
def load_img(file: str) -> SDL_Surface
def save_bmp(surface: SDL_Surface, file: str) -> None
def get_image_formats() -> list[str]# Core SDL2 types
class SDL_Window: ...
class SDL_Renderer: ...
class SDL_Texture: ...
class SDL_Surface:
flags: int
format: SDL_PixelFormat
w: int
h: int
pitch: int
pixels: ctypes.c_void_p
class SDL_Event:
type: int
class SDL_Rect:
x: int
y: int
w: int
h: int
class SDL_Color:
r: int
g: int
b: int
a: int
class SDL_PixelFormat:
format: int
palette: SDL_Palette
BitsPerPixel: int
BytesPerPixel: int
Rmask: int
Gmask: int
Bmask: int
Amask: int
class SDL_Palette:
ncolors: int
colors: SDL_Color
version: int
refcount: int
class SDL_RWops:
"""File I/O abstraction structure for reading/writing data."""
class SDL_Joystick:
"""Opaque joystick structure for raw joystick access."""
class SDL_GameController:
"""Opaque game controller structure for standardized controller input."""
# Timer callback type
SDL_TimerCallback = "function(interval: int, param: Any) -> int"
class SDL_AudioSpec:
freq: int
format: int
channels: int
silence: int
samples: int
size: int
# SDL2_mixer types
class Mix_Chunk:
"""Loaded audio clip for playback with the mixer API."""
allocated: int
abuf: bytes
alen: int
volume: int
# SDL2_ttf types
class TTF_Font:
"""Opaque data type for fonts opened using the TTF library."""
# Extension types
class Window:
size: tuple[int, int]
position: tuple[int, int]
title: str
class Renderer:
logical_size: tuple[int, int]
color: tuple[int, int, int, int]
class Sprite:
x: int
y: int
size: tuple[int, int]