3

I have a mouse listener:

from pynput.mouse import Listener, Button

def on_click(x, y, button):
    if button == Button.left:
    xy_dict["x"] = x
    xy_dict["y"] = y
    if button == Button.right:
        raise MyException(button)

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

And I also have main() function from other script. It is supposed that main() takes x and y from mouse listener, but how can I unite these two threads?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
bswan
  • 57
  • 5

1 Answers1

1

The context manager method (i.e. with) is only useful if you want to be able to stop the listener. If you don't need that, simply start the listener:

listener = Listener(on_click=on_click)
listener.start()

It will automatically start as a new thread:

https://pythonhosted.org/pynput/mouse.html#monitoring-the-mouse

A mouse listener is a threading.Thread, and all callbacks will be invoked from the thread.

The easiest method to access the x and y values would be to wrap this in a class and update instance attributes within the handler; or define two global variables (x and y).

Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • I also add that there is `listener.stop()` which can be used at the end of program to stop thread. And after `.stop()` we can use `listener.join()` – furas Aug 23 '19 at 00:03