Search code examples
pythonpython-3.xmousepyautogui

How to make the mouse cursor's position only update in the monitor when the python program says so?


In python turtle, if the program says "Screen.tracer(0)", then any changes can be made in the screen and they will only appear once "Screen.update()" is said. I'd like to know if there is a way to make it possible with the mouse cursor so that it can be moved as much as wanted, but until the program says so, it would remain in the same position.

I didn't find any solutions to this. I tried to keep the mouse in one position by repeatadly using "pyautogui.moveTo()", but when I was moving the mouse fast enough, the cursor left that position and then did move back, but I'd like it to stay there completely.


Solution

  • Use pynput. (pip install pynput)

    import pynput

    To have the mouse freeze:

    mouse_listener = pynput.mouse.Listener(suppress=True)
    mouse_listener.start()
    

    To unfreeze it: mouse_listener.stop()


    Note: freezing the mouse can get you stuck in a few ways if you don't implement it properly the first time. You should be able to Alt + F4 to end the process, though.

    Hope this helps!