Search code examples
python-3.xlinuxubuntumouseeventpynput

Mouse input not blocked when running Python code on Ubuntu using pynput library


I want to achieve the goal of blocking mouse signals while running the program, meaning I hope to disable the mouse through the above code. However, after executing it on Ubuntu, the mouse still functions. Could you please advise on how I can modify it to achieve the intended purpose? try.py:


from pynput import mouse

# Define the mouse event handler
def on_click(x, y, button, pressed):
    # In this example, we simply block the action of the mouse button
    return False  # Returning False to indicate blocking the event

# Listen for mouse events
with mouse.Listener(on_click=on_click) as listener:
    # Start listening for mouse events
    listener.join()

# When the program exits, the listener will be automatically closed, and the mouse will resume normal operation

Why my mouse still functions when I run the above Python code on Ubuntu?

I hope to receive pointed out errors or suggestions for modifying the code, and successfully disable the mouse using Python.


Solution

  • It's very simple, just add the argument suppress:

    from pynput.mouse import Listener
    
    def on_click(x, y, button, pressed):
        #do stuff here, do not return False or the mouse blocking will stop
    
    with Listener(on_click=on_click, suppress=True) as listener:
        listener.join()
    

    Ok, a few things to note. You don't have to import mouse from pynput, if you're only using the listener, use: from pynput.mouse import Listener.

    Second of all, if you want the mouse blocking to continue, you need to keep the listener running. When the listener terminates, then normal mouse function resumes.

    Finally, just note that adding the argument suppress=True allows for the mouse to be blocked. This will disable the mouse, so be careful with this code.