How to Move a Mouse with Python using the pyautogui module 


               


How to Move a Mouse with Python using the pyautogui Module



Python


In this article, we show how to move a mouse with Python using the pyautogui module.

pyautogui is a modle that can do many different dynamic things, including sending virtual keypresses and mouse clicks to Windows.

In this code, we will show how you can use the module to move the mouse cursor across the screen.

To do this, we use the pyautogui.moveTo() function. This function allows us to move the mouse cursor anywhere on the screen.

To get yourself situated with the pixels on your screen, you may first want to get how many pixels there are in width and length on the screen. This can be done with the pyautogui.size() function. When this function is run, you get returned the dimensions of the screen. This can serve as a reference of where you may want the mouse to go.

So, I want to the mouse cursor to go near the top left hand corner of the screen, so I write the following code shown below.



So the first thing that I must do is import pyautogui.

I then have the code, pyautogui.moveTo(100,100, duration=0.5)

This moves the mouse 100 pixels to the right and 100 pixels from the top of the screen.

In our next code below, we create a for loop in which the mouse cursor moves horizontally across the screen a set number of times in repetition.



So, in the code, we must first import pyautogui.

After this, we have a for loop that will loop through the block of code 3 times.

We then call, pyautogui.moveTo() function. What this function does is it will move the mouse cursor to the x- and y-coordinates for specified duration of seconds that you specify.

So when this code is run, the mouse cursor will go to point 100,100.

The mouse will then go to point 200,100

The mouse will then go to point 300,100

Since all we're doing is increasing the x-coordinates, the mouse moves horizontally across from left to right.

Since we created a for loop that loops 3 times through the code, the mouse will move horizontally across from left to right 3 times.

This is pretty cool actually to watch.

What's the use of this? Well, it could be used if you're demonstrating some type of program in which you want the mouse cursor to move automatically. Basically, any program where you want mouse movement automated.

And this is how the mouse can be moved with Python using the pyautogui module.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...