import pynput
import time
def poschange(x,y):
#print(f"{x},{y}")
print("poschange called")
pynput.mouse.Controller().position = (0,0)
def stop(key):
#print(key)
try:
if key.char == 'a':
print("stopped")
keyli.stop()
mouli.stop()
exit()
except:
pass
keyli = pynput.keyboard.Listener(on_press = stop)
keyli.start()
mouli = pynput.mouse.Listener(on_move = poschange)
mouli.start()
keyli.join()
mouli.join()
I just want to lock the mouse position when of the the mouse to (0,0) until I press the 'a' key on the keyboard and then the program terminates and i get control my mouse again.
To my knowledge in this code when ever i move the mouse the poschange()
method is called and the mouse position must be set back to (0,0) and repeat again until the mouse listener thread is terminated, but it just works twice, the print statement in the poschange()
function is printed twice in the console and then the mouse becomes sluggish and moves slowly, when I press 'a' the listeners must stop and program must terminate but it doesn't I have to manually do it and only the the mouse becomes fast and normal again. But when I remove the line pynput.mouse.Controller().position = (0,0)
from the code the thing works as i intend, it prints the print statement "poschange called" every time I move the mouse and the program terminates as expected when I press the 'a' key.
can someone please tell me why and tell me whats wrong with this. Thanks in advance.
You've created a recursion with that call to .position
as you move the cursor position in a callback triggered when a cursor changes its position.
I suppose you may get expected behavior by calling that
pynput.mouse.Controller().position = (0,0)
upon application start and by preventing the event propagation with:
mouli = pynput.mouse.Listener(on_move=poschange, suppress=True)