Essay record

P5 Python: How to get mouse position

Record
Essay / / 1 min read / 119 words
Tags
p5p5pypython
On this page2 sections / +

DISCLOSURE: Some links may be affiliate links. Details

problem

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.

solution

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)
    stroke(Color("#be403b"))
    background(204)

def draw():

    circle((mouse_x, mouse_y), 1)

def key_pressed(event):
    background(204)

run()

Built with CloudSeed Rust