2

I would like to record and append to a list the x and y coordinates of limited number of mouse clicks (10 in this case (This will be a variable)). The script needs to record the clicks over the desktop, browsers or applications in general.

I am basically trying to create a list of coordinates for a flexible simple macro section of a larger program for desktop automation (Very simple and repetitive work but the layout does change that is why re-recording the coordinates is key).

I have searched through "Automate the boring stuff" and cant get pyautogui to record the positions (It does execute mouse positions perfectly but not the pre-recording list). Also this cannot be limited to a single frame as seems to be the case in pygame.

Im a noob any advice would be appreciated. I have included an image of the error I receive. The list portion is not included yet I will add that later.

from pynput import mouse

NumberOfMouseClicks = 0

def on_click(x, y, button, pressed):
    print(x, y)
    pynput.mouse.Listener.stop

while NumberOfMouseClicks < 10 :
    NumberOfMouseClicks = NumberOfMouseClicks + 1
    with mouse.Listener(on_click=on_click) as listener:
        listener.join()

enter image description here

1 Answers1

6

You have not imported the pynput package only mouse from it. So instead of

pynput.mouse.Listener.stop

you should use

mouse.Listener.stop

The mouse event is handled in the on_click function, the while loop is useless. You can use it so:

from pynput import mouse

class MyException(Exception):pass

NumberOfMouseClicks = 0

def on_click(x, y, button, pressed):
    global NumberOfMouseClicks
    print(x, y)
    NumberOfMouseClicks = NumberOfMouseClicks + 1
    if (NumberOfMouseClicks==10):
        raise MyException(button)

with mouse.Listener(on_click=on_click) as listener:
    try:
        listener.join()
    except MyException as e:
        pass
quantummind
  • 2,086
  • 1
  • 14
  • 20
  • Thanks for the response, its printing every click perfectly in the terminal but it still exceeds the "while loop statement" is less than 10, Seems like I am stuck in one instance of the listener and its not incrementing as I may have expected, will read up more now. – python-constrictor Apr 02 '17 at 22:47
  • Yes, it is an other issue, the event is handled in the `on_click` function, so you should count there. I give an example in the answer. – quantummind Apr 02 '17 at 23:12
  • 1
    You are welcome. Please consider upvoting the answer. – quantummind Apr 03 '17 at 05:11