2

I'm trying to save the mouse's x and y coordinates when the mouse button is pressed and, separately, when it is released. I am able to print them but unable to save them to variables.

Here's what I got:

from pynput.mouse import Listener

def on_click(x, y, button, pressed):
    print('{0} at {1}'.format(
        'Pressed' if pressed else 'Released',
        (x, y)))
    if not pressed:
        # Stop listener
        return False

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

And then how would I call these variables on a global scale to use with another module (e.g. pyautogui?)

aschultz
  • 1,658
  • 3
  • 20
  • 30

2 Answers2

3

You've got pretty much everything in place, so I only had to add a few lines. Globals aren't the very best way to do things, but since this program isn't too complex, they will do the job.

The initial values of down_x, etc. don't really matter, as they will be overwritten, but they have to be there, or Python will throw an error.

#if you want to delay between mouse clicking, uncomment the line below
#import time
from pynput.mouse import Listener
import pyautogui

down_x = down_y = up_x = up_y = -1

def on_click(x, y, button, pressed):
    global down_x
    global down_y
    global up_x
    global up_y
    if pressed:
        (down_x, down_y) = (x, y)
    else:
        (up_x, up_y) = (x, y)
        return False

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

print("Mouse drag from", down_x, ",", down_y, "to", up_x, ",", up_y)

# you may wish to import the time module to make a delay
#time.sleep(1)
pyautogui.mouseDown(down_x, down_y)
#time.sleep(1)
pyautogui.mouseUp(up_x, up_y)
aschultz
  • 1,658
  • 3
  • 20
  • 30
0

Use global variables:

from pynput.mouse import Listener

xx, yy = 0, 0

def on_click(x, y, button, pressed):
    global xx, yy
    xx, yy = x, y
    print('{0} at {1}'.format(
        'Pressed' if pressed else 'Released',
        (x, y)))
    if not pressed:
        # Stop listener
        return False

with Listener(on_click=on_click) as listener:
    listener.join()
    # here you can read xx and yy

If your code gets more complicated you can consider wrapping it up in a class.

Tomasz Sabała
  • 1,204
  • 12
  • 16