Pure Python wrapper around SDL2 libraries for cross-platform multimedia development
npx @tessl/cli install tessl/pypi-pysdl2@0.9.00
# PySDL2
1
2
PySDL2 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.
3
4
## Package Information
5
6
- **Package Name**: PySDL2
7
- **Language**: Python
8
- **Installation**: `pip install PySDL2`
9
- **Dependencies**: SDL2 binaries (installable via `pip install pysdl2-dll`)
10
- **Python Support**: 2.7, 3.8-3.13 (CPython, PyPy)
11
12
## Core Imports
13
14
```python
15
import sdl2
16
import sdl2.ext
17
```
18
19
Module-level imports:
20
21
```python
22
import sdl2.video
23
import sdl2.events
24
import sdl2.render
25
import sdl2.ext.window
26
import sdl2.ext.renderer
27
```
28
29
## Basic Usage
30
31
```python
32
import sdl2
33
import sdl2.ext
34
35
# Initialize SDL2 extensions
36
sdl2.ext.init()
37
38
# Create a window
39
window = sdl2.ext.Window("Hello PySDL2", size=(800, 600))
40
window.show()
41
42
# Create a renderer for hardware-accelerated graphics
43
renderer = sdl2.ext.Renderer(window)
44
45
# Main event loop
46
running = True
47
while running:
48
events = sdl2.ext.get_events()
49
for event in events:
50
if event.type == sdl2.SDL_QUIT:
51
running = False
52
53
# Clear screen with blue color
54
renderer.clear((0, 100, 200))
55
56
# Present the rendered frame
57
renderer.present()
58
59
# Cleanup
60
sdl2.ext.quit()
61
```
62
63
## Architecture
64
65
PySDL2 provides a two-tier architecture:
66
67
- **Core Bindings (`sdl2.*`)**: Low-level ctypes wrappers that mirror SDL2's C API exactly, providing direct access to all SDL2 functionality with minimal overhead
68
- **Extensions (`sdl2.ext.*`)**: High-level Pythonic classes and utilities built on the core bindings, offering simplified interfaces for common tasks
69
70
This design allows developers to choose between direct SDL2 control (core) and Python convenience (extensions), often mixing both approaches within the same application.
71
72
## Capabilities
73
74
### Window and Display Management
75
76
Window creation, display mode handling, and OpenGL context management. Provides both low-level window control and high-level window classes.
77
78
```python { .api }
79
# Core window functions
80
def SDL_CreateWindow(title: bytes, x: int, y: int, w: int, h: int, flags: int) -> SDL_Window
81
def SDL_DestroyWindow(window: SDL_Window) -> None
82
def SDL_ShowWindow(window: SDL_Window) -> None
83
84
# Extension window class
85
class Window:
86
def __init__(self, title: str, size: tuple[int, int] = (800, 600), position: tuple[int, int] = None, flags: int = 0)
87
def show(self) -> None
88
def hide(self) -> None
89
```
90
91
[Window and Display Management](./window-display.md)
92
93
### Event Handling and Input
94
95
Comprehensive event system for keyboard, mouse, joystick, and system events. Includes both polling and event-driven approaches.
96
97
```python { .api }
98
# Core event functions
99
def SDL_PollEvent(event: SDL_Event) -> int
100
def SDL_WaitEvent(event: SDL_Event) -> int
101
102
# Extension event utilities
103
def get_events() -> list[SDL_Event]
104
def key_pressed(key: int) -> bool
105
def mouse_clicked() -> bool
106
```
107
108
[Event Handling and Input](./events-input.md)
109
110
### Joystick and Game Controller Input
111
112
Complete joystick and game controller support with both raw joystick access and standardized game controller mapping.
113
114
```python { .api }
115
# Joystick functions
116
def SDL_NumJoysticks() -> int
117
def SDL_JoystickOpen(device_index: int) -> SDL_Joystick
118
def SDL_JoystickClose(joystick: SDL_Joystick) -> None
119
def SDL_JoystickNumAxes(joystick: SDL_Joystick) -> int
120
def SDL_JoystickNumButtons(joystick: SDL_Joystick) -> int
121
def SDL_JoystickGetAxis(joystick: SDL_Joystick, axis: int) -> int
122
def SDL_JoystickGetButton(joystick: SDL_Joystick, button: int) -> int
123
124
# Game controller functions
125
def SDL_GameControllerOpen(joystick_index: int) -> SDL_GameController
126
def SDL_GameControllerClose(gamecontroller: SDL_GameController) -> None
127
def SDL_GameControllerGetAxis(gamecontroller: SDL_GameController, axis: int) -> int
128
def SDL_GameControllerGetButton(gamecontroller: SDL_GameController, button: int) -> int
129
```
130
131
[Joystick and Game Controller Input](./joystick-input.md)
132
133
### Graphics and Rendering
134
135
Software and hardware-accelerated rendering with support for textures, primitives, and surface operations.
136
137
```python { .api }
138
# Core rendering functions
139
def SDL_CreateRenderer(window: SDL_Window, index: int, flags: int) -> SDL_Renderer
140
def SDL_RenderClear(renderer: SDL_Renderer) -> int
141
def SDL_RenderPresent(renderer: SDL_Renderer) -> None
142
143
# Extension renderer class
144
class Renderer:
145
def __init__(self, target: Window, index: int = -1, flags: int = 0)
146
def clear(self, color: tuple[int, int, int] = (0, 0, 0)) -> None
147
def present(self) -> None
148
```
149
150
[Graphics and Rendering](./graphics-rendering.md)
151
152
### Audio System
153
154
Audio playback, recording, and mixing capabilities through SDL2_mixer integration.
155
156
```python { .api }
157
# Core audio functions
158
def SDL_OpenAudioDevice(device: bytes, iscapture: int, desired: SDL_AudioSpec, obtained: SDL_AudioSpec, allowed_changes: int) -> int
159
def SDL_CloseAudioDevice(dev: int) -> None
160
161
# Mixer functions
162
def Mix_OpenAudio(frequency: int, format: int, channels: int, chunksize: int) -> int
163
def Mix_LoadWAV(file: bytes) -> Mix_Chunk
164
def Mix_PlayChannel(channel: int, chunk: Mix_Chunk, loops: int) -> int
165
```
166
167
[Audio System](./audio.md)
168
169
### Timer and Timing
170
171
High-precision timing functions for animations, frame rate control, and custom timer callbacks.
172
173
```python { .api }
174
def SDL_GetTicks() -> int
175
def SDL_GetTicks64() -> int
176
def SDL_Delay(ms: int) -> None
177
def SDL_GetPerformanceCounter() -> int
178
def SDL_GetPerformanceFrequency() -> int
179
def SDL_AddTimer(interval: int, callback: SDL_TimerCallback, param: int) -> int
180
def SDL_RemoveTimer(timer_id: int) -> bool
181
```
182
183
[Timer and Timing](./timer.md)
184
185
### File I/O and Resource Loading
186
187
File I/O abstraction layer supporting files, memory buffers, and custom data sources through SDL_RWops.
188
189
```python { .api }
190
def SDL_RWFromFile(file: bytes, mode: bytes) -> SDL_RWops
191
def SDL_RWFromMem(mem: bytes, size: int) -> SDL_RWops
192
def SDL_RWFromConstMem(mem: bytes, size: int) -> SDL_RWops
193
def SDL_RWclose(context: SDL_RWops) -> int
194
def SDL_RWread(context: SDL_RWops, ptr: bytes, size: int, num: int) -> int
195
def SDL_RWwrite(context: SDL_RWops, ptr: bytes, size: int, num: int) -> int
196
def SDL_RWseek(context: SDL_RWops, offset: int, whence: int) -> int
197
```
198
199
[File I/O and Resource Loading](./file-io.md)
200
201
### System Integration and Utilities
202
203
System integration functions for clipboard access, file system paths, platform detection, and power management.
204
205
```python { .api }
206
# Clipboard functions
207
def SDL_SetClipboardText(text: bytes) -> int
208
def SDL_GetClipboardText() -> bytes
209
def SDL_HasClipboardText() -> bool
210
211
# File system functions
212
def SDL_GetBasePath() -> bytes
213
def SDL_GetPrefPath(org: bytes, app: bytes) -> bytes
214
215
# Platform detection
216
def SDL_GetPlatform() -> bytes
217
218
# Power management
219
def SDL_GetPowerInfo(secs: int, pct: int) -> int
220
```
221
222
[System Integration and Utilities](./system-utils.md)
223
224
### Sprite and Animation System
225
226
High-level sprite management, animation, and rendering systems for 2D games and applications.
227
228
```python { .api }
229
class Sprite:
230
def __init__(self, x: int = 0, y: int = 0)
231
232
class SpriteFactory:
233
def __init__(self, sprite_type: int = TEXTURE, renderer: Renderer = None)
234
def from_image(self, fname: str) -> Sprite
235
def from_color(self, color: tuple[int, int, int, int], size: tuple[int, int]) -> Sprite
236
237
class SpriteRenderSystem:
238
def render(self, sprites: list[Sprite]) -> None
239
```
240
241
[Sprite and Animation System](./sprites-animation.md)
242
243
### Font and Text Rendering
244
245
TrueType font loading and text rendering through SDL2_ttf integration.
246
247
```python { .api }
248
# TTF functions
249
def TTF_Init() -> int
250
def TTF_OpenFont(file: bytes, ptsize: int) -> TTF_Font
251
def TTF_RenderText_Solid(font: TTF_Font, text: bytes, fg: SDL_Color) -> SDL_Surface
252
253
# Extension font classes
254
class FontTTF:
255
def __init__(self, font_path: str, size: int)
256
def render(self, text: str, color: tuple[int, int, int] = (255, 255, 255)) -> SDL_Surface
257
258
class FontManager:
259
def add(self, font_path: str, alias: str = None, size: int = 16) -> None
260
def get(self, alias: str, size: int = 16) -> FontTTF
261
```
262
263
[Font and Text Rendering](./fonts-text.md)
264
265
### Image Loading and Processing
266
267
Image loading, saving, and manipulation through SDL2_image integration.
268
269
```python { .api }
270
# Image loading functions
271
def IMG_Load(file: bytes) -> SDL_Surface
272
def IMG_LoadTexture(renderer: SDL_Renderer, file: bytes) -> SDL_Texture
273
274
# Extension image utilities
275
def load_img(file: str) -> SDL_Surface
276
def save_bmp(surface: SDL_Surface, file: str) -> None
277
def get_image_formats() -> list[str]
278
```
279
280
[Image Loading and Processing](./image-processing.md)
281
282
## Types
283
284
```python { .api }
285
# Core SDL2 types
286
class SDL_Window: ...
287
class SDL_Renderer: ...
288
class SDL_Texture: ...
289
class SDL_Surface:
290
flags: int
291
format: SDL_PixelFormat
292
w: int
293
h: int
294
pitch: int
295
pixels: ctypes.c_void_p
296
297
class SDL_Event:
298
type: int
299
300
class SDL_Rect:
301
x: int
302
y: int
303
w: int
304
h: int
305
306
class SDL_Color:
307
r: int
308
g: int
309
b: int
310
a: int
311
312
class SDL_PixelFormat:
313
format: int
314
palette: SDL_Palette
315
BitsPerPixel: int
316
BytesPerPixel: int
317
Rmask: int
318
Gmask: int
319
Bmask: int
320
Amask: int
321
322
class SDL_Palette:
323
ncolors: int
324
colors: SDL_Color
325
version: int
326
refcount: int
327
328
class SDL_RWops:
329
"""File I/O abstraction structure for reading/writing data."""
330
331
class SDL_Joystick:
332
"""Opaque joystick structure for raw joystick access."""
333
334
class SDL_GameController:
335
"""Opaque game controller structure for standardized controller input."""
336
337
# Timer callback type
338
SDL_TimerCallback = "function(interval: int, param: Any) -> int"
339
340
class SDL_AudioSpec:
341
freq: int
342
format: int
343
channels: int
344
silence: int
345
samples: int
346
size: int
347
348
# SDL2_mixer types
349
class Mix_Chunk:
350
"""Loaded audio clip for playback with the mixer API."""
351
allocated: int
352
abuf: bytes
353
alen: int
354
volume: int
355
356
# SDL2_ttf types
357
class TTF_Font:
358
"""Opaque data type for fonts opened using the TTF library."""
359
360
# Extension types
361
class Window:
362
size: tuple[int, int]
363
position: tuple[int, int]
364
title: str
365
366
class Renderer:
367
logical_size: tuple[int, int]
368
color: tuple[int, int, int, int]
369
370
class Sprite:
371
x: int
372
y: int
373
size: tuple[int, int]
374
```