Cross-platform library for developing multimedia applications and video games in Python built on top of SDL
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.
import pygame.key
import pygame.mouse
import pygame.joystickMonitor keyboard state and handle key events with support for key codes, modifiers, and key repeat settings.
def get_pressed() -> ScancodeWrapper:
"""
Get the state of all keyboard keys.
Returns:
ScancodeWrapper: Sequence-like object with boolean values for each key
"""
def get_mods() -> int:
"""
Get the state of keyboard modifier keys.
Returns:
int: Bitmask of active modifier keys (KMOD_* constants)
"""
def set_mods(mods: int) -> None:
"""
Set the state of keyboard modifier keys.
Args:
mods (int): Bitmask of modifier keys to activate
"""
def get_focused() -> bool:
"""
Check if the display window has keyboard focus.
Returns:
bool: True if window has keyboard focus
"""
def name(key: int, use_compat: bool = True) -> str:
"""
Get the name of a key from its key code.
Args:
key (int): Key code constant
use_compat (bool): Use compatibility names for some keys
Returns:
str: Key name (e.g., "space", "escape", "a")
"""
def key_code(name: str) -> int:
"""
Get key code from key name.
Args:
name (str): Key name
Returns:
int: Key code constant
"""
def set_repeat(delay: int = 0, interval: int = 0) -> None:
"""
Control key repeat behavior.
Args:
delay (int): Delay before repeat starts in ms (0 disables repeat)
interval (int): Interval between repeats in ms
"""
def get_repeat() -> tuple[int, int]:
"""
Get current key repeat settings.
Returns:
tuple[int, int]: (delay, interval) in milliseconds
"""Handle text input for typing and international keyboard support with input method editors (IME).
def start_text_input() -> None:
"""Start text input mode for receiving TEXTINPUT events."""
def stop_text_input() -> None:
"""Stop text input mode."""
def set_text_input_rect(rect: pygame.Rect | None) -> None:
"""
Set the rectangle for text input composition.
Args:
rect (pygame.Rect | None): Area where text input occurs, None to clear
"""Track mouse position, button states, and relative movement for mouse-based interaction.
def get_pos() -> tuple[int, int]:
"""
Get current mouse cursor position.
Returns:
tuple[int, int]: (x, y) position relative to window
"""
def get_rel() -> tuple[int, int]:
"""
Get relative mouse movement since last call.
Returns:
tuple[int, int]: (dx, dy) movement in pixels
"""
def set_pos(pos: tuple[int, int]) -> None:
"""
Set mouse cursor position.
Args:
pos (tuple[int, int]): (x, y) position to move cursor to
"""
def get_pressed(num_buttons: int = 3) -> tuple[bool, ...]:
"""
Get current state of mouse buttons.
Args:
num_buttons (int): Number of buttons to check (3 or 5)
Returns:
tuple[bool, ...]: Button states (left, middle, right, x1, x2)
"""
def get_focused() -> bool:
"""
Check if the display window has mouse focus.
Returns:
bool: True if window has mouse focus
"""Control mouse cursor appearance and visibility with support for system cursors, bitmap cursors, and color cursors.
def set_visible(visible: bool) -> bool:
"""
Set mouse cursor visibility.
Args:
visible (bool): True to show cursor, False to hide
Returns:
bool: Previous visibility state
"""
def get_visible() -> bool:
"""
Get mouse cursor visibility.
Returns:
bool: True if cursor is visible
"""
def set_cursor(*args) -> None:
"""
Set mouse cursor appearance. Multiple call signatures:
- set_cursor(system: int) - Set to system cursor
- set_cursor(size, hotspot, xormasks, andmasks) - Set bitmap cursor
- set_cursor(hotspot, surface) - Set color cursor from surface
"""
def get_cursor() -> tuple:
"""
Get current cursor data.
Returns:
tuple: Cursor data (format varies by cursor type)
"""# Character keys
K_a: int
K_b: int
K_c: int
# ... through K_z
# Number keys
K_0: int
K_1: int
K_2: int
# ... through K_9
# Special keys
K_SPACE: int
K_RETURN: int
K_ESCAPE: int
K_BACKSPACE: int
K_TAB: int
K_DELETE: int
# Arrow keys
K_UP: int
K_DOWN: int
K_LEFT: int
K_RIGHT: int
# Function keys
K_F1: int
K_F2: int
# ... through K_F15
# Modifier keys
K_LSHIFT: int
K_RSHIFT: int
K_LCTRL: int
K_RCTRL: int
K_LALT: int
K_RALT: int
# Keypad
K_KP0: int
K_KP1: int
# ... through K_KP9
K_KP_ENTER: int
K_KP_PLUS: int
K_KP_MINUS: int
# Modifier masks
KMOD_NONE: int
KMOD_LSHIFT: int
KMOD_RSHIFT: int
KMOD_SHIFT: int
KMOD_LCTRL: int
KMOD_RCTRL: int
KMOD_CTRL: int
KMOD_LALT: int
KMOD_RALT: int
KMOD_ALT: int# Mouse button numbers
BUTTON_LEFT: int # 1
BUTTON_MIDDLE: int # 2
BUTTON_RIGHT: int # 3
BUTTON_WHEELUP: int # 4
BUTTON_WHEELDOWN: int # 5
BUTTON_X1: int # 6
BUTTON_X2: int # 7
# System cursor types
SYSTEM_CURSOR_ARROW: int
SYSTEM_CURSOR_IBEAM: int
SYSTEM_CURSOR_WAIT: int
SYSTEM_CURSOR_CROSSHAIR: int
SYSTEM_CURSOR_WAITARROW: int
SYSTEM_CURSOR_SIZENWSE: int
SYSTEM_CURSOR_SIZENESW: int
SYSTEM_CURSOR_SIZEWE: int
SYSTEM_CURSOR_SIZENS: int
SYSTEM_CURSOR_SIZEALL: int
SYSTEM_CURSOR_NO: int
SYSTEM_CURSOR_HAND: intimport pygame
import pygame.key
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
# Set up key repeat
pygame.key.set_repeat(500, 50) # 500ms delay, 50ms interval
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
print(f"Key pressed: {pygame.key.name(event.key)}")
# Check current key states
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
print("Moving left")
if keys[pygame.K_RIGHT]:
print("Moving right")
# Check modifier keys
mods = pygame.key.get_mods()
if mods & pygame.KMOD_SHIFT:
print("Shift is held")
if mods & pygame.KMOD_CTRL:
print("Ctrl is held")
clock.tick(60)
pygame.quit()import pygame
import pygame.key
pygame.init()
screen = pygame.display.set_mode((800, 600))
font = pygame.font.Font(None, 36)
text = ""
input_active = False
# Enable text input
pygame.key.start_text_input()
# Set input area for IME
input_rect = pygame.Rect(100, 100, 600, 40)
pygame.key.set_text_input_rect(input_rect)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.TEXTINPUT:
# Handle text input (Unicode support)
text += event.text
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_BACKSPACE:
text = text[:-1]
elif event.key == pygame.K_RETURN:
print(f"Entered: {text}")
text = ""
elif event.key == pygame.K_ESCAPE:
# Toggle text input mode
if input_active:
pygame.key.stop_text_input()
else:
pygame.key.start_text_input()
input_active = not input_active
screen.fill((255, 255, 255))
# Draw input box
color = (0, 200, 0) if input_active else (200, 200, 200)
pygame.draw.rect(screen, color, input_rect, 2)
# Render text
text_surface = font.render(text, True, (0, 0, 0))
screen.blit(text_surface, (input_rect.x + 5, input_rect.y + 5))
pygame.display.flip()
pygame.quit()import pygame
import pygame.mouse
pygame.init()
screen = pygame.display.set_mode((800, 600))
# Set system cursor
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_CROSSHAIR)
running = True
drawing = False
last_pos = None
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == pygame.BUTTON_LEFT:
drawing = True
last_pos = event.pos
elif event.button == pygame.BUTTON_RIGHT:
# Toggle cursor visibility
visible = pygame.mouse.get_visible()
pygame.mouse.set_visible(not visible)
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == pygame.BUTTON_LEFT:
drawing = False
last_pos = None
elif event.type == pygame.MOUSEMOTION:
if drawing and last_pos:
# Draw line from last position
pygame.draw.line(screen, (255, 0, 0), last_pos, event.pos, 3)
last_pos = event.pos
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
# Clear screen
screen.fill((0, 0, 0))
elif event.key == pygame.K_s:
# Change cursor to system arrow
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
elif event.key == pygame.K_h:
# Change cursor to hand
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)
# Show mouse info
mouse_pos = pygame.mouse.get_pos()
mouse_buttons = pygame.mouse.get_pressed()
# Draw cursor position
if pygame.mouse.get_visible():
font = pygame.font.Font(None, 24)
pos_text = font.render(f"Mouse: {mouse_pos}", True, (255, 255, 255))
screen.blit(pos_text, (10, 10))
if mouse_buttons[0]: # Left button
button_text = font.render("Left button pressed", True, (255, 255, 0))
screen.blit(button_text, (10, 35))
pygame.display.flip()
pygame.quit()import pygame
import pygame.mouse
pygame.init()
screen = pygame.display.set_mode((800, 600))
# Create custom cursor from surface
cursor_surface = pygame.Surface((32, 32), pygame.SRCALPHA)
pygame.draw.circle(cursor_surface, (255, 0, 0, 128), (16, 16), 15)
pygame.draw.circle(cursor_surface, (255, 255, 255), (16, 16), 15, 2)
# Set color cursor
pygame.mouse.set_cursor((16, 16), cursor_surface)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
# System arrow cursor
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)
elif event.key == pygame.K_2:
# System crosshair
pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_CROSSHAIR)
elif event.key == pygame.K_3:
# Custom color cursor
pygame.mouse.set_cursor((16, 16), cursor_surface)
elif event.key == pygame.K_m:
# Move mouse to center
center = (screen.get_width() // 2, screen.get_height() // 2)
pygame.mouse.set_pos(center)
elif event.key == pygame.K_r:
# Get relative movement (resets internal counters)
rel_x, rel_y = pygame.mouse.get_rel()
print(f"Relative movement: ({rel_x}, {rel_y})")
# Check mouse focus
has_focus = pygame.mouse.get_focused()
screen.fill((0, 0, 0))
# Show focus status
font = pygame.font.Font(None, 36)
focus_text = "Mouse focused" if has_focus else "No mouse focus"
color = (0, 255, 0) if has_focus else (255, 0, 0)
text_surface = font.render(focus_text, True, color)
screen.blit(text_surface, (10, 10))
# Instructions
instructions = [
"1 - Arrow cursor",
"2 - Crosshair cursor",
"3 - Custom cursor",
"M - Move to center",
"R - Show relative movement"
]
for i, instruction in enumerate(instructions):
inst_surface = font.render(instruction, True, (255, 255, 255))
screen.blit(inst_surface, (10, 60 + i * 30))
pygame.display.flip()
pygame.quit()