Mouse input
Read the mouse position, detect clicks on objects, drag things around and use the scroll wheel, by building a small paint program.
On this page
What you'll learn
- Mouse events versus
pygame.mouse.get_pressed() - Detecting clicks on buttons and objects
- Drawing continuous lines while dragging
- Using the scroll wheel and changing the cursor
Prerequisites: Keyboard input.
Mouse events#
Like the keyboard, the mouse produces events and has a state you can poll.
| Event | Useful attributes | When it fires |
|---|---|---|
MOUSEBUTTONDOWN | pos, button | a button is pressed |
MOUSEBUTTONUP | pos, button | a button is released |
MOUSEMOTION | pos, rel, buttons | the mouse moves |
MOUSEWHEEL | x, y | the wheel or trackpad scrolls |
event.button is 1 for left, 2 for middle and 3 for right. Older code also uses buttons 4 and 5 for the wheel; in Pygame 2 use the MOUSEWHEEL event and its y value (positive scrolls up).
For state, pygame.mouse.get_pos() returns the current (x, y) and pygame.mouse.get_pressed() returns (left, middle, right) booleans.
Clicking on things#
To know whether a click hit something, ask the object's Rect:
if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if play_button.collidepoint(event.pos):
start_game()For circles, compare the distance instead: pygame.Vector2(event.pos).distance_to(center) <= radius. For irregular sprites you can use masks; see collision detection.
A paint program#
This program uses every technique on this page. The left button paints, the right button erases, the wheel changes the brush size, and clicking a swatch picks a colour.
"""A tiny paint program: left button draws, right button erases, wheel changes the brush."""
import pygame
WIDTH, HEIGHT = 640, 480
COLORS = [(21, 35, 63), (232, 93, 82), (91, 147, 230), (110, 200, 120), (244, 197, 49)]
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 24)
canvas = pygame.Surface((WIDTH, HEIGHT - 40))
canvas.fill("white")
brush = 8
color_index = 0
last_pos = None
palette = [pygame.Rect(10 + i * 34, HEIGHT - 32, 26, 26) for i in range(len(COLORS))]
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
for i, swatch in enumerate(palette):
if swatch.collidepoint(event.pos): # clicked a colour swatch
color_index = i
elif event.type == pygame.MOUSEWHEEL:
brush = max(2, min(40, brush + event.y * 2)) # event.y is +1 or -1
elif event.type == pygame.MOUSEBUTTONUP:
last_pos = None
buttons = pygame.mouse.get_pressed() # (left, middle, right)
mx, my = pygame.mouse.get_pos()
if my < HEIGHT - 40 and (buttons[0] or buttons[2]):
color = COLORS[color_index] if buttons[0] else (255, 255, 255)
if last_pos:
pygame.draw.line(canvas, color, last_pos, (mx, my), brush * 2)
pygame.draw.circle(canvas, color, (mx, my), brush)
last_pos = (mx, my)
else:
last_pos = None
screen.blit(canvas, (0, 0))
pygame.draw.rect(screen, (230, 234, 240), (0, HEIGHT - 40, WIDTH, 40))
for i, swatch in enumerate(palette):
pygame.draw.rect(screen, COLORS[i], swatch)
if i == color_index:
pygame.draw.rect(screen, (0, 0, 0), swatch.inflate(6, 6), 2)
screen.blit(font.render(f"Brush {brush}px (mouse wheel) Right button erases", True, (21, 35, 63)), (200, HEIGHT - 28))
if my < HEIGHT - 40:
pygame.draw.circle(screen, (120, 120, 120), (mx, my), brush, 1) # brush outline
pygame.display.flip()
clock.tick(120)
pygame.quit()Why the lines? Even at 120 FPS a fast mouse moves many pixels between frames. Drawing only a circle at each position leaves dotted gaps, so the program remembers last_pos and draws a thick line from there to the new position. The painting goes onto a separate canvas Surface that is never cleared, while the screen is redrawn each frame with the canvas, the palette bar and the brush outline on top.
Dragging objects#
Dragging needs three steps: on button down, find the object under the cursor and remember the offset between its position and the mouse; on motion, move it to mouse plus offset; on button up, let go. The mouse interaction example in Pygame Online shows this with draggable circles.
The cursor#
pygame.mouse.set_visible(False)hides the system cursor, useful when you draw your own crosshair.pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_HAND)switches to a hand pointer, for example while hovering a button.pygame.event.set_grab(True)keeps the mouse inside the window, which suits shooters with mouse look. Always give players a way to release it, such as Escape.
Common mistakes#
- Using
get_pressed()for clicks: a click lasts several frames, so a "button" triggers repeatedly. UseMOUSEBUTTONDOWNfor clicks. - Ignoring which button: without checking
event.button == 1, scrolling or right-clicking also counts as a click. - Scaled windows: if you scale your game surface yourself, mouse coordinates are in window pixels. Divide by the scale, or use
pygame.SCALED, which converts coordinates for you. See screen sizes and scaling. - Touchscreens: touches arrive as mouse events by default, but there is no hover and no right button. Design touch-friendly buttons.
Practice exercises#
- Add a "clear canvas" button that wipes the drawing.
- Save the drawing with
pygame.image.save(canvas, "drawing.png")when you press Ctrl+S. - Add a fill tool, or straight lines drawn while holding Shift.
- Make hovered swatches grow slightly, and change the cursor to a hand over them.