How to stop all listeners (keyboard and mouse) at the same time?

138 Views Asked by At

The task:

  1. Track the coordinates of a mouse click or key press on the keyboard
  2. Press ESC to end both keyboard and mouse tracking at the same time.

Question: Pressing ESC stops keyboard tracking, but mouse tracking continues. How to stop mouse_listener process at the same time?

Code:

from pynput import keyboard
from pynput import mouse

def on_press(key):
    if key == keyboard.Key.esc:
        print("EXIT")
        return False
    print(key)

def on_click(x, y, button, pressed):
    print(str(x) + " " + str(y))

mouse_listener = mouse.Listener(on_click=on_click)
keyboard_listener = keyboard.Listener(on_press=on_press)
keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()

Additional questions:

  1. Why does clicking once execute on_press(key) twice?

enter image description here

  1. Why on_press=on_press is highlighted in PyCharm? Although code isexecuted without any error, but PyCharm obviously does not like it.

enter image description here

1

There are 1 best solutions below

1
paradoxarium On

UPDATE: With user h4z3 assistance - the problems is solved as follows:

To stop mouse_listener it is necessary to stop the process correctly:

mouse_listener.stop()

In order to exclude the second processing of the mouse click, it is necessary to exclude the release of the button (Pressed = True, Released = False):

if pressed:
    print(str(x) + " " + str(y))

Final code:

from pynput import keyboard
from pynput import mouse

def on_press(key):
    if key == keyboard.Key.esc:
        print("EXIT")
        mouse_listener.stop()
        return False
    print(key)

def on_click(x, y, button, pressed):
    if pressed:
        print(str(x) + " " + str(y))


mouse_listener = mouse.Listener(on_click=on_click)
keyboard_listener = keyboard.Listener(on_press=on_press)
keyboard_listener.start()
mouse_listener.start()
keyboard_listener.join()
mouse_listener.join()