Get the Current live Positions of Your Mouse using Python

Get the current live positions of your mouse cursor using a python script.

Introduction

Suppose, you want to create an Automation script that will accomplish a certain task that you have done manually till the present. For instance, a python program that will open a browser by clicking, search for present weather report, and let you know about it. Before going to make such a kind of automation script you need to learn how to click an object present on the screen.

In this tutorial, we'll learn how to get the current position of a mouse cursor on the screen using a python program. Because it's almost impossible to figure out the exact cursor position by looking on the screen. Our python program will show

1. The current X-and Y coordinates of the mouse cursor.

2. Update those coordinates as the mouse moves around the screen.

🔹Visit AlsoCreate a Screen Recorder📽 using Python - Very Easy to Use

Requirements

Install PyAutoGUI: pip install PyAutoGUI

Import the Module

Start your program with the following:


import pyautogui

print("Press Ctrl-C to quit.")

It imports the PyAutoGUI module and shows a reminder to the user that they have to print Ctrl-C to stop.

Get Mouse Coordinates

Get the coordinates of your mouse cursor using python code.

Set an infinite loop to get the current mouse coordinates from mouse.position() and print that. Next, you need to catch the keyboard interrupt exception, which will raise whenever the user will press Ctrl+C.


try:
while True:
x, y = pyautogui.position()
positionString = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)

You need to print the coordinate format nicely so that it looks presentable. X-and Y variables are two integers. So, we passed these integer coordinates to the str() function to get the result in the string form. 

The rjust() method will right-justify them so that they take up the same amount of space, whether the coordinate has one, two, three, or four digits. By concatenating the right-justified string coordinates with 'X: ' and 'Y: ' labels gives a nicely formatted string. which will be stored in positionString variable.

Print the Mouse Coordinates


print(positionString, end='')
print('\b' * len(positionString), end='', flush=True)
except KeyboardInterrupt:
print('\nDone.')

You can erase the most recent line of text you've already printed on the screen. Once you print a newline, you can't erase anything before it. The end='' keyword argument to the print() function prevents the default newline character from being added to the end of the previous printed line of text.

Let's see the yellow line. To erase characters, print the \b backspace escape character. It counts the length of the printed string and erases the string by printing the same amount of \b characters. Pass flush=True to update the text as desired.

The while loop repeats so quickly. That's why the user won't notice that you're deleting and reprinting the whole text on the screen repeatedly until the user press Ctrl-C.

Full Code


import pyautogui

print("Press Ctrl-C to quit.")
try:
while True:
x, y = pyautogui.position()
positionString = 'X: ' + str(x).rjust(4) + ' Y: ' + str(y).rjust(4)
print(positionString, end='')
print('\b' * len(positionString), end='', flush=True)
except KeyboardInterrupt:
print('\nDone.')

The Output

🔹Visit AlsoPassword Strength Checker in Python - with Regex

Conclusion

In this tutorial, you've learned how to get the live update of the current positions of a mouse cursor. We made a simple python script to get that. You can use it to make a GUI automation.

In the next upcoming topics, I will create a practical example to use this python program. Let me know in the comment section what automation script you would like to make using this python code we discussed here.

You can get more lovely unique programming examples from  this blog. Learn those also.

Thanks for reading!💙

Subhankar Rakshit

Meet Subhankar Rakshit, a Computer Science postgraduate (M.Sc.) and the creator of PySeek. Subhankar is a programmer, specializes in Python language. With a several years of experience under his belt, he has developed a deep understanding of software development. He enjoys writing blogs on various topics related to Computer Science, Python Programming, and Software Development.

Post a Comment (0)
Previous Post Next Post