or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

advanced-drawing.mdaudio-sound.mdcore-system.mddrawing-shapes.mdevent-input.mdgame-objects.mdgraphics-display.mdindex.mdinput-devices.mdjoystick-gamepad.mdmath-utils.mdsurface-image.mdtext-font.mdtime-animation.mdtransform-image.md

input-devices.mddocs/

0

# Input Devices

1

2

Keyboard, mouse, and joystick input handling including state checking, position tracking, and device configuration. Pygame provides comprehensive support for various input devices with both event-based and polling-based input methods.

3

4

```python

5

import pygame.key

6

import pygame.mouse

7

import pygame.joystick

8

```

9

10

## Capabilities

11

12

### Keyboard Input

13

14

Monitor keyboard state and handle key events with support for key codes, modifiers, and key repeat settings.

15

16

```python { .api }

17

def get_pressed() -> ScancodeWrapper:

18

"""

19

Get the state of all keyboard keys.

20

21

Returns:

22

ScancodeWrapper: Sequence-like object with boolean values for each key

23

"""

24

25

def get_mods() -> int:

26

"""

27

Get the state of keyboard modifier keys.

28

29

Returns:

30

int: Bitmask of active modifier keys (KMOD_* constants)

31

"""

32

33

def set_mods(mods: int) -> None:

34

"""

35

Set the state of keyboard modifier keys.

36

37

Args:

38

mods (int): Bitmask of modifier keys to activate

39

"""

40

41

def get_focused() -> bool:

42

"""

43

Check if the display window has keyboard focus.

44

45

Returns:

46

bool: True if window has keyboard focus

47

"""

48

49

def name(key: int, use_compat: bool = True) -> str:

50

"""

51

Get the name of a key from its key code.

52

53

Args:

54

key (int): Key code constant

55

use_compat (bool): Use compatibility names for some keys

56

57

Returns:

58

str: Key name (e.g., "space", "escape", "a")

59

"""

60

61

def key_code(name: str) -> int:

62

"""

63

Get key code from key name.

64

65

Args:

66

name (str): Key name

67

68

Returns:

69

int: Key code constant

70

"""

71

72

def set_repeat(delay: int = 0, interval: int = 0) -> None:

73

"""

74

Control key repeat behavior.

75

76

Args:

77

delay (int): Delay before repeat starts in ms (0 disables repeat)

78

interval (int): Interval between repeats in ms

79

"""

80

81

def get_repeat() -> tuple[int, int]:

82

"""

83

Get current key repeat settings.

84

85

Returns:

86

tuple[int, int]: (delay, interval) in milliseconds

87

"""

88

```

89

90

### Text Input

91

92

Handle text input for typing and international keyboard support with input method editors (IME).

93

94

```python { .api }

95

def start_text_input() -> None:

96

"""Start text input mode for receiving TEXTINPUT events."""

97

98

def stop_text_input() -> None:

99

"""Stop text input mode."""

100

101

def set_text_input_rect(rect: pygame.Rect | None) -> None:

102

"""

103

Set the rectangle for text input composition.

104

105

Args:

106

rect (pygame.Rect | None): Area where text input occurs, None to clear

107

"""

108

```

109

110

### Mouse Input

111

112

Track mouse position, button states, and relative movement for mouse-based interaction.

113

114

```python { .api }

115

def get_pos() -> tuple[int, int]:

116

"""

117

Get current mouse cursor position.

118

119

Returns:

120

tuple[int, int]: (x, y) position relative to window

121

"""

122

123

def get_rel() -> tuple[int, int]:

124

"""

125

Get relative mouse movement since last call.

126

127

Returns:

128

tuple[int, int]: (dx, dy) movement in pixels

129

"""

130

131

def set_pos(pos: tuple[int, int]) -> None:

132

"""

133

Set mouse cursor position.

134

135

Args:

136

pos (tuple[int, int]): (x, y) position to move cursor to

137

"""

138

139

def get_pressed(num_buttons: int = 3) -> tuple[bool, ...]:

140

"""

141

Get current state of mouse buttons.

142

143

Args:

144

num_buttons (int): Number of buttons to check (3 or 5)

145

146

Returns:

147

tuple[bool, ...]: Button states (left, middle, right, x1, x2)

148

"""

149

150

def get_focused() -> bool:

151

"""

152

Check if the display window has mouse focus.

153

154

Returns:

155

bool: True if window has mouse focus

156

"""

157

```

158

159

### Mouse Cursor

160

161

Control mouse cursor appearance and visibility with support for system cursors, bitmap cursors, and color cursors.

162

163

```python { .api }

164

def set_visible(visible: bool) -> bool:

165

"""

166

Set mouse cursor visibility.

167

168

Args:

169

visible (bool): True to show cursor, False to hide

170

171

Returns:

172

bool: Previous visibility state

173

"""

174

175

def get_visible() -> bool:

176

"""

177

Get mouse cursor visibility.

178

179

Returns:

180

bool: True if cursor is visible

181

"""

182

183

def set_cursor(*args) -> None:

184

"""

185

Set mouse cursor appearance. Multiple call signatures:

186

187

- set_cursor(system: int) - Set to system cursor

188

- set_cursor(size, hotspot, xormasks, andmasks) - Set bitmap cursor

189

- set_cursor(hotspot, surface) - Set color cursor from surface

190

"""

191

192

def get_cursor() -> tuple:

193

"""

194

Get current cursor data.

195

196

Returns:

197

tuple: Cursor data (format varies by cursor type)

198

"""

199

```

200

201

## Key Constants

202

203

```python { .api }

204

# Character keys

205

K_a: int

206

K_b: int

207

K_c: int

208

# ... through K_z

209

210

# Number keys

211

K_0: int

212

K_1: int

213

K_2: int

214

# ... through K_9

215

216

# Special keys

217

K_SPACE: int

218

K_RETURN: int

219

K_ESCAPE: int

220

K_BACKSPACE: int

221

K_TAB: int

222

K_DELETE: int

223

224

# Arrow keys

225

K_UP: int

226

K_DOWN: int

227

K_LEFT: int

228

K_RIGHT: int

229

230

# Function keys

231

K_F1: int

232

K_F2: int

233

# ... through K_F15

234

235

# Modifier keys

236

K_LSHIFT: int

237

K_RSHIFT: int

238

K_LCTRL: int

239

K_RCTRL: int

240

K_LALT: int

241

K_RALT: int

242

243

# Keypad

244

K_KP0: int

245

K_KP1: int

246

# ... through K_KP9

247

K_KP_ENTER: int

248

K_KP_PLUS: int

249

K_KP_MINUS: int

250

251

# Modifier masks

252

KMOD_NONE: int

253

KMOD_LSHIFT: int

254

KMOD_RSHIFT: int

255

KMOD_SHIFT: int

256

KMOD_LCTRL: int

257

KMOD_RCTRL: int

258

KMOD_CTRL: int

259

KMOD_LALT: int

260

KMOD_RALT: int

261

KMOD_ALT: int

262

```

263

264

## Mouse Constants

265

266

```python { .api }

267

# Mouse button numbers

268

BUTTON_LEFT: int # 1

269

BUTTON_MIDDLE: int # 2

270

BUTTON_RIGHT: int # 3

271

BUTTON_WHEELUP: int # 4

272

BUTTON_WHEELDOWN: int # 5

273

BUTTON_X1: int # 6

274

BUTTON_X2: int # 7

275

276

# System cursor types

277

SYSTEM_CURSOR_ARROW: int

278

SYSTEM_CURSOR_IBEAM: int

279

SYSTEM_CURSOR_WAIT: int

280

SYSTEM_CURSOR_CROSSHAIR: int

281

SYSTEM_CURSOR_WAITARROW: int

282

SYSTEM_CURSOR_SIZENWSE: int

283

SYSTEM_CURSOR_SIZENESW: int

284

SYSTEM_CURSOR_SIZEWE: int

285

SYSTEM_CURSOR_SIZENS: int

286

SYSTEM_CURSOR_SIZEALL: int

287

SYSTEM_CURSOR_NO: int

288

SYSTEM_CURSOR_HAND: int

289

```

290

291

## Usage Examples

292

293

### Keyboard Input Polling

294

295

```python

296

import pygame

297

import pygame.key

298

299

pygame.init()

300

screen = pygame.display.set_mode((800, 600))

301

clock = pygame.time.Clock()

302

303

# Set up key repeat

304

pygame.key.set_repeat(500, 50) # 500ms delay, 50ms interval

305

306

running = True

307

while running:

308

for event in pygame.event.get():

309

if event.type == pygame.QUIT:

310

running = False

311

elif event.type == pygame.KEYDOWN:

312

print(f"Key pressed: {pygame.key.name(event.key)}")

313

314

# Check current key states

315

keys = pygame.key.get_pressed()

316

317

if keys[pygame.K_LEFT]:

318

print("Moving left")

319

if keys[pygame.K_RIGHT]:

320

print("Moving right")

321

322

# Check modifier keys

323

mods = pygame.key.get_mods()

324

if mods & pygame.KMOD_SHIFT:

325

print("Shift is held")

326

if mods & pygame.KMOD_CTRL:

327

print("Ctrl is held")

328

329

clock.tick(60)

330

331

pygame.quit()

332

```

333

334

### Text Input Handling

335

336

```python

337

import pygame

338

import pygame.key

339

340

pygame.init()

341

screen = pygame.display.set_mode((800, 600))

342

font = pygame.font.Font(None, 36)

343

344

text = ""

345

input_active = False

346

347

# Enable text input

348

pygame.key.start_text_input()

349

350

# Set input area for IME

351

input_rect = pygame.Rect(100, 100, 600, 40)

352

pygame.key.set_text_input_rect(input_rect)

353

354

running = True

355

while running:

356

for event in pygame.event.get():

357

if event.type == pygame.QUIT:

358

running = False

359

elif event.type == pygame.TEXTINPUT:

360

# Handle text input (Unicode support)

361

text += event.text

362

elif event.type == pygame.KEYDOWN:

363

if event.key == pygame.K_BACKSPACE:

364

text = text[:-1]

365

elif event.key == pygame.K_RETURN:

366

print(f"Entered: {text}")

367

text = ""

368

elif event.key == pygame.K_ESCAPE:

369

# Toggle text input mode

370

if input_active:

371

pygame.key.stop_text_input()

372

else:

373

pygame.key.start_text_input()

374

input_active = not input_active

375

376

screen.fill((255, 255, 255))

377

378

# Draw input box

379

color = (0, 200, 0) if input_active else (200, 200, 200)

380

pygame.draw.rect(screen, color, input_rect, 2)

381

382

# Render text

383

text_surface = font.render(text, True, (0, 0, 0))

384

screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 5))

385

386

pygame.display.flip()

387

388

pygame.quit()

389

```

390

391

### Mouse Input and Cursor Control

392

393

```python

394

import pygame

395

import pygame.mouse

396

397

pygame.init()

398

screen = pygame.display.set_mode((800, 600))

399

400

# Set system cursor

401

pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_CROSSHAIR)

402

403

running = True

404

drawing = False

405

last_pos = None

406

407

while running:

408

for event in pygame.event.get():

409

if event.type == pygame.QUIT:

410

running = False

411

elif event.type == pygame.MOUSEBUTTONDOWN:

412

if event.button == pygame.BUTTON_LEFT:

413

drawing = True

414

last_pos = event.pos

415

elif event.button == pygame.BUTTON_RIGHT:

416

# Toggle cursor visibility

417

visible = pygame.mouse.get_visible()

418

pygame.mouse.set_visible(not visible)

419

elif event.type == pygame.MOUSEBUTTONUP:

420

if event.button == pygame.BUTTON_LEFT:

421

drawing = False

422

last_pos = None

423

elif event.type == pygame.MOUSEMOTION:

424

if drawing and last_pos:

425

# Draw line from last position

426

pygame.draw.line(screen, (255, 0, 0), last_pos, event.pos, 3)

427

last_pos = event.pos

428

elif event.type == pygame.KEYDOWN:

429

if event.key == pygame.K_c:

430

# Clear screen

431

screen.fill((0, 0, 0))

432

elif event.key == pygame.K_s:

433

# Change cursor to system arrow

434

pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)

435

elif event.key == pygame.K_h:

436

# Change cursor to hand

437

pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)

438

439

# Show mouse info

440

mouse_pos = pygame.mouse.get_pos()

441

mouse_buttons = pygame.mouse.get_pressed()

442

443

# Draw cursor position

444

if pygame.mouse.get_visible():

445

font = pygame.font.Font(None, 24)

446

pos_text = font.render(f"Mouse: {mouse_pos}", True, (255, 255, 255))

447

screen.blit(pos_text, (10, 10))

448

449

if mouse_buttons[0]: # Left button

450

button_text = font.render("Left button pressed", True, (255, 255, 0))

451

screen.blit(button_text, (10, 35))

452

453

pygame.display.flip()

454

455

pygame.quit()

456

```

457

458

### Advanced Mouse Features

459

460

```python

461

import pygame

462

import pygame.mouse

463

464

pygame.init()

465

screen = pygame.display.set_mode((800, 600))

466

467

# Create custom cursor from surface

468

cursor_surface = pygame.Surface((32, 32), pygame.SRCALPHA)

469

pygame.draw.circle(cursor_surface, (255, 0, 0, 128), (16, 16), 15)

470

pygame.draw.circle(cursor_surface, (255, 255, 255), (16, 16), 15, 2)

471

472

# Set color cursor

473

pygame.mouse.set_cursor((16, 16), cursor_surface)

474

475

running = True

476

while running:

477

for event in pygame.event.get():

478

if event.type == pygame.QUIT:

479

running = False

480

elif event.type == pygame.KEYDOWN:

481

if event.key == pygame.K_1:

482

# System arrow cursor

483

pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)

484

elif event.key == pygame.K_2:

485

# System crosshair

486

pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_CROSSHAIR)

487

elif event.key == pygame.K_3:

488

# Custom color cursor

489

pygame.mouse.set_cursor((16, 16), cursor_surface)

490

elif event.key == pygame.K_m:

491

# Move mouse to center

492

center = (screen.get_width() // 2, screen.get_height() // 2)

493

pygame.mouse.set_pos(center)

494

elif event.key == pygame.K_r:

495

# Get relative movement (resets internal counters)

496

rel_x, rel_y = pygame.mouse.get_rel()

497

print(f"Relative movement: ({rel_x}, {rel_y})")

498

499

# Check mouse focus

500

has_focus = pygame.mouse.get_focused()

501

502

screen.fill((0, 0, 0))

503

504

# Show focus status

505

font = pygame.font.Font(None, 36)

506

focus_text = "Mouse focused" if has_focus else "No mouse focus"

507

color = (0, 255, 0) if has_focus else (255, 0, 0)

508

text_surface = font.render(focus_text, True, color)

509

screen.blit(text_surface, (10, 10))

510

511

# Instructions

512

instructions = [

513

"1 - Arrow cursor",

514

"2 - Crosshair cursor",

515

"3 - Custom cursor",

516

"M - Move to center",

517

"R - Show relative movement"

518

]

519

520

for i, instruction in enumerate(instructions):

521

inst_surface = font.render(instruction, True, (255, 255, 255))

522

screen.blit(inst_surface, (10, 60 + i * 30))

523

524

pygame.display.flip()

525

526

pygame.quit()

527

```