The task:
- Track the coordinates of a mouse click or key press on the keyboard
- 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:
- Why does clicking once execute on_press(key) twice?
- Why on_press=on_press is highlighted in PyCharm? Although code isexecuted without any error, but PyCharm obviously does not like it.


UPDATE: With user h4z3 assistance - the problems is solved as follows:
To stop mouse_listener it is necessary to stop the process correctly:
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):
Final code: