Mouse Library in Python
Last Updated :
10 Jan, 2023
In this article, we will learn about the mouse library. In contrast to other Python modules, the Mouse Module enables us to fully control our mouse through a variety of features, including hooking global events, registering hotkeys, simulating mouse movement and clicks, and much more. The following are a few mouse features:
- Python can simulate a mouse click.
- Python may be used to find the location of the mouse cursor.
- Using Python, move the mouse cursor.
- Python can move the mouse cursor.
- Make sure the mouse clicks.
- Use the mouse wheel to navigate.
- Capture and playback of the mouse.
- Result of a mouse click.
To, install the mouse library we can use the following command:
pip install mouse
Simulating mouse clicks
You can send a click using mouse.click().
Python3
import mouse
mouse.click( 'left' )
mouse.click( 'right' )
mouse.click( 'middle' )
|
Get the Location of the Mouse Cursor using Python
Example 1: Using the mouse
Python3
mouse.get_position()
position = mouse.position()
print (position)
|
Output:
Example 2: Using pynput
Python3
from pynput.mouse import Button, Controller
mouse = Controller()
current_mouse_position = mouse.position
print (current_mouse_position)
|
Drag the Mouse Cursor using Python
Drag from 0, 0 to 50, 50 within the duration of 0.1 seconds.
Python3
mouse.drag( 0 , 0 , 50 , 50 , absolute = False , duration = 0.1 )
|
Move the mouse cursor using Python:
Moving the cursor 50 left and 50 right
Python3
mouse.move( 50 , 50 , absolute = False , duration = 0.2 )
|
Mouse cursor relative to its current position
Mouse cursor 10 pixels to the right and 20 pixels down from its current position
Python3
mouse.move_relative( 10 , 20 )
|
Check the Mouse Click
Here, the right button is clicked.
Python3
mouse.is_pressed( "right" )
|
Action the mouse:
Here, we are moving 50 right and 50 down.
Python3
mouse.move( 50 , 50 , absolute = False , duration = 0.2 )
|
Control the mouse wheel
It controls the scroll of the mouse.
Python3
mouse.wheel( - 1 )
mouse.wheel( 1 )
|
Scroll the mouse wheel
Python3
mouse.scroll( 10 )
mouse.scroll( - 5 )
|
Record and Replay
It Records the mouse movements.
Share your thoughts in the comments
Please Login to comment...