Cursor not moving to originial spot pynput

My current code looks like this:

from pynput.mouse import Button, Controller, Listener

mouse = Controller()

def on_click(x, y, button, pressed):
    if button == Button.right:
        placeX = x
        placeY = y
        mouse.position = (placeX, placeY) # Doesn't work. Why?


with Listener(
        on_click=on_click
) as listener:
    listener.join()

My goal is to put the cursor back to its original position after the right mouse button is released. When I was testing it, nothing happened. How do I get it to work?

Answer

Doesn’t work. Why?

Your current implemented logic looks like this:
On mouse click, if it is the right button (regardless of whether it is pressed or released), store the current mouse coordinates in placeX and placeY, and immediately move the mouse to that location.

Not very efficient as the mouse was already in this location.

How to fix?

Check if the mouse is released or not

def on_click(x, y, button, pressed):
    if pressed:
        ...  # remember the position
    else:
        ...  # return to position

Check mouse button

def on_click(x, y, button, pressed):
    if button != Button.right:
        return  # we don't care

    if pressed:
        ...  # remember the position
    else:
        ...  # return to position

Save original position

# in case the mouse was pressed and not released when starting the program
original_position = mouse.position

def on_click(x, y, button, pressed):
    if button != Button.right:
        return  # we don't care

    global original_position 

    if pressed:
        original_position = mouse.position  # remember the position
    else:
        mouse.position = original_position  # return to position

We use the keyword global here so that we can later change the value of a global variable.

Enjoy

🙂

Alternative

Note that I usually think of global as a code smell, so here’s a nicer and slightly more advanced solution with a class:

from pynput.mouse import Button, Controller, Listener

mouse = Controller()


class Mover:
    def __init__(self, original_position=mouse.position):
        self.original_position = original_position

    def on_click(self, x, y, button, pressed):
        if button != Button.right:
            return  # we don't care

        if pressed:
            self.original_position = mouse.position  # remember the position
        else:
            mouse.position = self.original_position  # return to position


mover = Mover()

with Listener(
        on_click=mover.on_click
) as listener:
    listener.join()