In my project I am required to do a task when the mouse is scrolled upwards.
I am using pynput and doing a task on Right click but I am not sure how to trigger something when the mouse wheel is scrolled upwards. Anny idea how to do it? I am open to using any other package as well for this purpose.
CodePudding user response:
I assume if you are calling a method on right click and you are able to do it without any problem then the issue is not with the code i think you need to look at the link mentioned in comment by Yevhen.
I think you did but still confused how to do it so let me put an example here.
def method_1(x,y,button,pressed):
print(x,y,button,pressed)
def method_2(x, y, button, scroll_direction):
print(x,y,button,scroll_direction)
listener = mouse.Listener(on_click=method_1,on_scroll=method_2)
listener.start()
listener.join()
This is how to do it. Method_1 will trigger on any click and method_2 will trigger on scroll in any direction.
CodePudding user response:
The first package we’ll discuss is pynput. One of the advantages of pynput is that is works on both Windows and macOS. Another nice feature is that it has functionality to monitor keyboard and mouse input. Let’s get started with pynput by installing it with pip:
1 pip install pynput Once you have it installed, you can get started by importing the Controller and Button classes. Then, we’ll create an instance of the Controller class, which we’ll call mouse. This will simulate your computer’s mouse to allow you to programmatically click buttons and move the mouse around on the screen.
1 2 3 from pynput.mouse import Button, Controller
mouse = Controller() Next, let’s look at a couple simple commands. To right or left-click, we can use the Button class imported above.
1 2 3 4 5
left-click
mouse.press(Button.left)
right-click
mouse.press(Button.right) To double click, you just need to add the number two as the second parameter.
1 mouse.press(Button.left, 2) We can also move the mouse pointer to a different position by using the move method.
1 2 3 mouse.move(50, -50)
mouse.move(100, -200) pynput can control the keyboard, as well. To do that, we need to import the Key class
1 from pynput.keyboard import Key To make your keyboard type, you can use the aptly-named keyboard.type method.
1 keyboard.type("this is a test")