P5 Python: How to get mouse position

Published: 2020-01-21 22:43:43 -0500 -0500

Reading time: 1 mins (115 words)

Tags: python p5 p5py


I’m using p5py - the Python port of the P5 library from Processing - to create some sketches in my journey through The Nature of Code. I want to use the mouse position as input.


Within your draw function, you can access the mouse’s x and y position via the mouse_x and mouse_y variables. These are automagically set behind the scenes within the p5 framework, so all you have to do is read the values.

Here’s an example p5py sketch that draws circles at the position of the mouse in every run of draw:

from p5 import *

def setup():
    size(640, 360)

def draw():

    circle((mouse_x, mouse_y), 1)

def key_pressed(event):


About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus