0

So I'm trying to write a python program that simulates a right mouse click whenever I scroll with the mouse. I tried using pynput, and this is what I have:

from pynput.mouse import Button, Controller, Listener

mouse = Controller()

def on_scroll(x, y, dx, dy):
    mouse.click(Button.left)
    print('Scrolled {0}'.format(
        (x, y)))


with Listener(
        on_scroll=on_scroll) as listener:
    listener.join()

Every time I run this program and scroll, my computer starts lagging, and my mouse as well. Then, I have to force shut down my computer because of the lag. What should I do?

Thank you in advance!

GGberry
  • 929
  • 5
  • 21

1 Answers1

1

The docs mention that you shouldn't put a blocking action in the scroll code. Since I can reproduce your issue, I assume that the mouse.click(Button.left) is a blocking action.

Which can be shown using:

from pynput.mouse import Controller, Events, Button

mouse = Controller()

if __name__ == '__main__':
    with Events() as events:
        for event in events:
            if isinstance(event, Events.Scroll):
                print(f'Scrolling event: {event}')
                mouse.click(Button.left)
            print(event)

This will run correctly for the mouse movements, until you start scrolling after which it gets stuck in an infinite loop. I will try and see if there is an alternative solution and edit it to the answer, but for now I haven't found one.

Edit

I haven't found any solution for this right now, it is mentioned on this post that the problem can be OS Specific. I can reproduce your claims on Windows, so you might want to create an Issue on pynput their package page.

Thymen
  • 2,089
  • 1
  • 9
  • 13
  • Thanks! That did it :) – GGberry Nov 30 '20 at 15:17
  • As mentioned in the solution, it is a one time fix. It will work once, after which the program hangs on the `mouse.click`. So I assume that there is a larger problem in their code code, that makes the `mouse.click` hanging on Windows. – Thymen Nov 30 '20 at 15:21