Open In App

Mouse Library in Python

Last Updated : 10 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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
 
# left click
mouse.click('left')
# right click
mouse.click('right')
# middle click
mouse.click('middle')


Get the Location of the Mouse Cursor using Python

Example 1: Using the mouse

Python3




# get the current location of your mouse
mouse.get_position()
#current position of the mouse using the "position" function
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)
#mouse cursor relative to its current position


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# scroll down
mouse.wheel(1# scroll up


Scroll the mouse wheel

Python3




mouse.scroll(10)   # Scroll the mouse wheel down by 10 units
mouse.scroll(-5)   # Scroll the mouse wheel up by 5 units


Record and Replay

It Records the mouse movements.

Python3




mouse.record()




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads