The Wayback Machine - https://web.archive.org/web/20241108193204/https://www.geeksforgeeks.org/gui-automation-using-python/
Open In App

GUI Automation using Python

Last Updated : 23 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will explore how we can do GUI automation using Python. There are many modules that can do these things, but in this article, we will use a module named PyAutoGUI to perform GUI and desktop automation using python. 

We would explore two sections –

  • How to automatically use the mouse pointer to perform certain tasks like moving the cursor, clicking on a certain point on the screen, etc
  • Also, we would explore how we can automate the keyboard keystrokes.

Installation

This module does not come preloaded with Python. To install it type the below command in the terminal.

pip install pyautogui # for windows
or 
pip3 install pyautogui #for linux and Macos

Getting Started

We should know the screen size of my device before doing any automation. Luckily PyautoGUI helps us to easily get it using the .size() function. It returns a size object with two values that represent the width and height of the screen respectively. Implementation is as follows.

Syntax: pyautogui.size()

Parameters: This function does not take any extra parameters

Return Type: It returns us the size of the present screen in pixels in a Size object 

Below is the implementation:

Python3




# importing modules
import pyautogui
 
# returns a size object with
# width and height of the screen
print(pyautogui.size())


Output:

Size(width=1920, height=1080)

Automating Mouse Movements

Getting the current position of the mouse cursor:

Firstly, we would where currently my mouse cursor is at, for that we can use the .position() function. The function again returns a point object with x and y values that gets the current position of the mouse.

Syntax: pyautogui.position()

Parameters: This function does not take any extra parameters

Return Type: It returns us the position of the mouse cursor in a Point object

Below is the implementation:

Python3




import pyautogui
 
# returns a point  object with
# x and y values
print(pyautogui.position())


Output:

Point(x=1710, y=81)

Moving the cursor and clicking on specific spots:

Now we would try to move the mouse cursor and click at specific spots and perform opening an application and closing it. For moving the mouse pointer we can use .moveto() and specify x,y values along with a duration in which it will perform the operation, and we would use the  .click() function to click on the spot where our mouse pointer is located right now. The code basically moves the mouse cursor to (519,1060) (x,y) values and then simulate a click using the .click()  where the cursor is situated right now, then we again move to the position (1717,352) using the moveTo() and simulate a click again. 

Syntax: pyautogui.moveTo() and pyautogui.click()

Parameters: This moveTo function has two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter. The click method in the example doesn’t take any parameter but an optional pair of parameters can be used to click a particular position on the keyboard.

Return Type: The functions don’t return anything but performs the jobs of the cursor to a specific point and then clicking there programmatically.  

Below is the implementation:

Python3




import pyautogui
 
 
# moves to (519,1060) in 1 sec
pyautogui.moveTo(519, 1060, duration = 1)
 
# simulates a click at the present
# mouse position
pyautogui.click()
 
# moves to (1717,352) in 1 sec
pyautogui.moveTo(1717, 352, duration = 1)
 
# simulates a click at the present
# mouse position
pyautogui.click()


Output:

Now we would explore two more methods namely .moveRel() which helps us to move relative to the position we are at right now and finally we would see how we can simulate a right-click using pyAutoGUI. We start with importing the package and stimulate the cursor to move  498 px & down 998px from its current position. Then we use the click() method to simulate a left-click. Then we move to a specific location using the .moveTo() method. Now we again click on the present position of the cursor but this time we instruct to simulate a right-click instead of left by passing the button=” right” parameter (default is button =” left”). Then we gain to move to a specified location and left click there.

Syntax: pyautogui.moveRel()

Parameters: This moveRel function has also two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter. Also, we used an extra parameter for the pyautogui.click() function, we used button=”right” which simulates a right-click instead of the default left-click.

 Return Type: The functions don’t return anything but perform the jobs of moving the cursor left 498 px & down 998px from it’s current position and then simulate a right-click programmatically. 

Below is the implementation:

Python3




import pyautogui
 
# moving the cursor left 498 px & down
# 998px from it's current position
pyautogui.moveRel(-498,996, duration = 1)
 
# clicks at the present location
pyautogui.click()
 
# moves to the specified location
pyautogui.moveTo(1165,637, duration = 1)
 
# right clicks at the present cursor
# location
pyautogui.click(button="right")
 
# moves to the specified location
pyautogui.moveTo(1207,621, duration = 1)
 
# clicks at the present location
pyautogui.click()


Output:

Dragging the cursor to a specific screen position:

Now we would see how can we drag windows using pyAutoGUI. We can use the .dragto() and .dragrel() which are exactly the way the .moveto() and .movrel() works except that in this case, they hold the left click while moving the cursor. In this program we simply, import the modules, then we move to a specified using the .moveTo() function. Then we left-click at the current position of the cursor. Now we again move the cursor to a specified location. Then we use the .dragTo() function to drag (left-click and hold) the to a specific location. Finally, we use the dragRel() function that drags the cursor relative to its current position to 50px right and 50 px down.

Syntax: pyautogui.dragTo() and pyautogui.dragRel()

Parameters: Both the functions has two required and one optional parameter, the first two values of x and y are required values while the duration is an extra parameter that kind of animates the movement of the mouse over the no of seconds assigned to the duration parameter.

Return Type: The functions don’t return anything but perform the jobs of left-click and holding and moves the cursor to (500,500) position and drags the cursor relative to it’s position to 5opx right and 50 px down programmatically. 

Below is the implementation:

Python3




import pyautogui
 
# cursor moves to a specific position
pyautogui.moveTo(519,1060, duration = 1)
 
# left clicks at the current position
pyautogui.click()
 
# cursor moves to a specific position
pyautogui.moveTo(1550,352, duration = 1)
 
# left clicks and holds and moves the
# cursor to (500,500) position
pyautogui.dragTo(500,500, duration = 1)
 
# drags the cursor relative to it's
# position to 5opx right and 50 px down
pyautogui.dragRel(50,50, duration=1)


Output:

Note: Duration parameter in .moveTo(), .moveRel(), .dragTo() and .dragRel() functions are optional, but it is provided to get a animation effect, without the property functions will execute instantly, and it would be tough to understand. Also we optionally pass x and y values in .click() function which can be used to click at a different location that the location the cursor is currently at.

Automating Keyboard

Automatically typing with keyboard:

First, we would learn how to simulate typing something using pyAutoGUI. Here in this example, we would type something in a notepad file using the .typewrite() function. In this code, we first import the time and pyAutoGUI module and then use time.sleep() function to pause the execution of the program for some specified seconds. Then we use the pyautogui.typewrite() function to simulate typing of alphanumeric keys. The phrase inside the quotes would be typed. Implementation is as follows:

Syntax: pyautogui.typewrite()

Parameters: The function has only one parameter which is the string that needs to be typed.

Return Type: The functions don’t return anything but perform the jobs of simulating the typing of a string that is passed inside it. 

Below is the implementation:

Python3




# used to access time related functions
import time
import pyautogui
 
# pauses the execution of the program
# for 5 sec
time.sleep(5)
 
# types the string passed inside the
# function
pyautogui.typewrite("Geeks For Geeks!")


Output:

Pressing specific keys and simulating hotkey:

Next, we would explore two functions, the first one is .press() and the second one is .hotkey(), first one helps you to press a key generally used to press non-alphanumeric keys and the .hotkeys() functions helps us to press hotkeys like ctrl+shift+esc, etc. Here also we start the code by importing two modules, time and pyAutoGUI. Then we pause the execution of the program for 5 seconds using the sleep function. we type the string using the typewrite function. Then we use the .press() function to simulate a keypress and finally the .hotkey() function to simulate the pressing of hotkeys. In our example, we used hotkey ctrl+a that selects all the text.  The implementation is as follows:

Syntax: pyautogui.press() and pyautogui.hotkey()

Parameters: The .press() function has only one parameter which is the key that needs to be pressed and the .hotkey() function has a number of parameters depending upon the number of keys to simulate the hotkey action.

Return Type: The functions don’t return anything but perform the job of simulating of pressing the enter key and simulates pressing the hotkey ctrl+a. 

Below is the implementation:

Python3




# used to access time related functions
import time
import pyautogui
 
# pauses the execution of the program
# for 5 sec
time.sleep(5)
 
# types the string passed inside the
# function
pyautogui.typewrite("Geeks For Geeks!")
 
# simulates pressing the enter key
pyautogui.press("enter")
 
# simulates pressing the hotkey ctrl+a
pyautogui.hotkey("ctrl","a")


Output:

Displaying message boxes

Now we would try to explore some cross-platform JavaScript style message boxes provided to us by pyAutoGUI. It uses Tkinter and PyMsgBox module to display these boxes. The code starts with importing modules, then we use different message boxes to display different messages. The .alert() function displays an alert in which we set the title and text to be blank with an “OK” button. Then the .confirm() function displays a confirm dialog box in which we again set the title and text to be blank and keep two buttons “OK” & “CANCEL” button. Then the .prompt() function displays a confirmation prompt box in which we again set the title, text, and default (what would be written by default in the prompt box before the user starts typing) to be blank. Finally, the .password() function displays a password dialog box in which we again set the title and text to be blank and set the mask (The character that gets replaced instead of the original letters in the password) to be “*”. The implementation is as follows:

Syntax: pyautogui.alert(), pyautogui.confirm(), pyautogui.prompt() and pyautogui.password()

Parameters: The .alert() function has three parameters defining the title, text and buttons to be placed. The .confirm() function also has three parameters for text, title and buttons. The .prompt() function has three parameters for text, title and default value. The .password() has four parameters for text, title, default value and mask (The character that gets replaced instead of the original letters in the password).  

Return Type: The functions don’t return anything but show up an alert in which we set the title and text to be blank with an “OK” button. Then it displays a confirm dialogue box in which we again set the title and text to be blank and keep two buttons “OK” & “CANCEL” button. Then the .prompt() function displays a confirmation prompt box in which we again set the title, text and default (what would be written by default in the prompt box before the user starts typing) to be blank. Finally, the .password() function displays a password dialogue box in which we again set the title and text to be blank and set the mask to be “*”. 

Below is the implementation:

Python3




import pyautogui
 
  
# a alert displays with a ok button
# on it
pyautogui.alert(text='', title='', button='OK')
 
# a confirm dialog box appears with ok
# and cancel buttons on it
pyautogui.confirm(text='', title='', buttons=['OK', 'Cancel'])
 
# a prompt displays that lets you to
# write something
pyautogui.prompt(text='', title='' , default='')
 
# a password field appears with entry box
# to fill a password
pyautogui.password(text='', title='', default='', mask='*')


Output:

Taking screenshots

Finally, we would see how to take a screenshot using pyAutoGUI using the .screenshot() function. We would start by importing the pyAutoGUI module. Then we use the .screenshot() function that takes a screenshot of the present window and stores it as “123.png” in the same directory, for storing in another directory, we need to provide its relative or absolute path. The implementation would be as follows:

Syntax: pyautogui.screenshot()

Parameters: The function has one optional parameter which is the path of the file along with the filename in which the screenshot needs to be stored.

Return Type: The function doesn’t return anything but takes a screenshot and stores it in the path passed inside it as a parameter.

Below is the implementation:

Python3




import pyautogui
 
# takes a screenshot of the present
# window and stores it as "123.png"
pyautogui.screenshot("123.png")


Output:



Similar Reads

Using lambda in GUI programs in Python
Python Lambda Functions are anonymous function means that the function is without a name. In this article, we will learn to use lambda functions in Tkinter GUI. We use lambda functions to write our code more efficiently and to use one function many times by passing different arguments. We use the lambda function to pass arguments to other functions
3 min read
Python | Simple GUI calculator using Tkinter
Prerequisite: Tkinter Introduction, lambda function Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI a
6 min read
Python | Distance-time GUI calculator using Tkinter
Prerequisites : Introduction to Tkinter | Using google distance matrix API Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter outputs the fastest and easiest wa
7 min read
Cryptography GUI using python
Using cryptography techniques we can generate keys for a plain text which can not be predicted easily. We use Cryptography to ensure the safe and secure flow of data from one source to another without being accessed by a malicious user. Prerequisites: Language used - Python. Tkinter - This module is used to make GUIs using python language. To know
4 min read
Python | Create a GUI Marksheet using Tkinter
Create a python GUI mark sheet. Where credits of each subject are given, enter the grades obtained in each subject and click on Submit. The credits per subject, the total credits as well as the SGPA are displayed after being calculated automatically. Use Tkinter to create the GUI interface. Refer the below articles to get the idea about basics of t
8 min read
Python: Weight Conversion GUI using Tkinter
Prerequisites: Python GUI – tkinterPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to create GUI applications. Crea
2 min read
Python | ToDo GUI Application using Tkinter
Prerequisites : Introduction to tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create a ToDo GUI application using Tkinter, with a step-by-step guide. To create a tkinter : Importing the module – tkinter
5 min read
Python | GUI Calendar using Tkinter
Prerequisites: Introduction to Tkinter Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a GUI Calendar application using
4 min read
Sentiment Detector GUI using Tkinter - Python
Prerequisites : Introduction to tkinter | Sentiment Analysis using Vader Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to creat
4 min read
Python - Morse Code Translator GUI using Tkinter
Prerequisites : Introduction to tkinter | Morse Code Translator Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a Morse
6 min read
Python - SpongeBob Mocking Text Generator GUI using Tkinter
Prerequisites : Introduction to tkinter | SpongeBob Mocking Text Generator Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to cre
4 min read
Python - Spell Corrector GUI using Tkinter
Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. Python with Tkinter outputs the fastest and easiest way to create GUI applications. In this article, we will learn how to create a GUI Spell Corrector application using Tkinter, with a step-by-step gu
5 min read
Python - UwU text convertor GUI using Tkinter
Prerequisites :Introduction to tkinter | UwU text convertor Python offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter outputs the fastest and easiest way to crea
4 min read
GST Rate Finder GUI using Python-Tkinter
Prerequisites : Introduction to tkinter | Program to calculate GSTPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. In this article, we will learn how to create GST Rate Finder GUI application using Tkinter, with a step-by-step guide. To create a Tki
3 min read
Create GUI for Downloading Youtube Video using Python
Prerequisites: Python GUI – tkinter YouTube is a very popular video-sharing website. Downloading a video's/playlist from YouTube is a tedious task. Downloading that video through Downloader or trying to download it from a random website increase's the risk of licking your personal data. Using the Python Tkinter package, this task is very simple-eff
12 min read
Create Copy-Move GUI using Tkinter in Python
Everyone reading this post is well aware of the importance of Copying the file or moving the file from one specific location to another. In this post, we have tried to explain not only the program but added some exciting pieces of Interface. Up to now, many of you may get about what we are talking about. Yes, you are right, We are going to use "Tki
4 min read
Python - English (Latin) to Hindi (Devanagiri) text convertor GUI using Tkinter
Prerequisites : Introduction to tkinter | Text transliteration from English to Indian languages – Using indic-transliterationPython offers multiple options for developing a GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python
4 min read
Standard GUI Unit Converter using Tkinter in Python
Prerequisites: Introduction to tkinter, Introduction to webbrowser In this article, we will learn how to create a standard converter using tkinter. Now we are going to create an introduction window that displays loading bar, welcome text, and user's social media profile links so that when he/she shares his code with some others, they can contact th
12 min read
GUI chat application using Tkinter in Python
Chatbots are computer program that allows user to interact using input methods. The Application of chatbots is to interact with customers in big enterprises or companies and resolve their queries. Chatbots are mainly built for answering standard FAQs. The benefit of this type of system is that customer is no longer required to follow the same tradi
7 min read
Login Application and Validating info using Kivy GUI and Pandas in Python
Prerequisites : Kivy, Pandas Kivy is a multiplatform GUI library, known for being responsive. It provides management of multiple screens in a single application. In this application we will be using multiple screens to log in user's info and validate it. We will save the information in a csv file and use pandas to validate the information inside of
5 min read
Text to speech GUI convertor using Tkinter in Python
Prerequisite: Introduction to Tkinter Tkinter is the standard GUI library for Python. Python when combined with tkinter provides a fast and easy way to create GUI applications.By this library we can make a compelling choice for building GUI applications in Python, especially for applications where a modern sheen is unnecessary, and the top priority
3 min read
Build a GUI Application to Get Live Stock Price using Python
The stock price is the highest amount someone is willing to pay for the stock. In this article, we are going to write code for getting live share prices for each company and bind it with GUI Application. Module Needed Yahoo_fin: This module is used to scrape historical stock price data, as well as to provide current information on market caps, divi
3 min read
Build a Voice Recorder GUI using Python
Prerequisites: Python GUI – tkinter, Create a Voice Recorder using Python Python provides various tools and can be used for various purposes. One such purpose is recording voice. It can be done using the sounddevice module. This recorded file can be saved using the soundfile module Module NeededSounddevice: The sounddevice module provides bindings
2 min read
Build a GUI Application to get distance between two places using Python
Prerequisite: Tkinter In this article, we are going to write a python script to get the distance between two places and bind it with the GUI application. To install the GeoPy module, run the following command in your terminal. pip install geopy Approach used: Import the geopy module.Initialize Nominatim API to get location from the input string.Get
2 min read
Create a GUI to get Sunset and Sunrise time using Python.
Prerequisite: Tkinter module In this article, we are going to write python scripts to get sunset and sunrise time and bind it with the GUI application. Before starting we need to understand suntime and geopy module Modules Needed: suntime module: This module will return the sunset and sunrise time calculation python library. Run this command in you
3 min read
Create a GUI to Extract information from VIN number Using Python
Prerequisite: Python GUI – tkinter In this article, we are going to look at how can we use Python to extract vehicle information from its VIN number (Vehicle Identification Number). A VIN consists of 17 characters (digits and capital letters) that act as a unique identifier for the vehicle. It is a unique code that is assigned to every motor vehicl
3 min read
GUI Application for Live Cricket scoreboard Using Python
In this article, we will see how sports.py module is imported and implemented to produce scoreboard of a specified sport like baseball, basketball, cricket and many more along with other details about the sport. Code examples in the text below revolve around cricket, you can perform the same operation for any other sport. Sport.py Scrapes data from
3 min read
GUI application to search a country name from a given state or city name using Python
In these articles, we are going to write python scripts to search a country from a given state or city name and bind it with the GUI application. We will be using the GeoPy module. GeoPy modules make it easier to locate the coordinates of addresses, cities, countries, landmarks, and Zipcode. Before starting we need to install the GeoPy module, so l
2 min read
Build an GUI Application to Get Live Air Quality Information Using Python.
We are living in a modernization and industrialization era. Our life becomes more and more convenient. But the problem is Air Pollution arise with time. This Pollution makes us unhealthy, Air is a Lifeline for our life. In this article, we are going to write python scripts to get live air quality information and bind it with GUI Application. Module
5 min read
Create a GUI to search bank information with IFSC Code using Python
Prerequisite: Python GUI – tkinter The following program depicts how a GUI application can be formulated using python script to get bank details by using IFSC code. Here, we are using Razorpay IFSC Toolkit to fetch IFSC code. Razorpay IFSC Toolkit processes IFSC codes via their toolkit and return data set. Module Needed: requests Requests allows yo
3 min read
Practice Tags :
three90RightbarBannerImg