GUI Automation using Python
Last Updated :
23 Jan, 2023
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
Python Tutorial - Learn Python Programming Language Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. It'sA high-level language, used in web development, data science, automation, AI and more.Known fo
10 min read
Python Fundamentals
Python IntroductionPython was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in PythonUnderstanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython's input() function
7 min read
Python VariablesIn Python, variables are used to store data that can be referenced and manipulated during program execution. A variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python variables do not require explicit declaration of type. The type of the variable i
6 min read
Python OperatorsIn Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators. OPERATORS: These are the special symbols. Eg- + , * , /,
6 min read
Python KeywordsKeywords in Python are reserved words that have special meanings and serve specific purposes in the language syntax. Python keywords cannot be used as the names of variables, functions, and classes or any other identifier. Getting List of all Python keywordsWe can also get all the keyword names usin
2 min read
Python Data TypesPython Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Conditional Statements in PythonConditional statements in Python are used to execute certain blocks of code based on specific conditions. These statements help control the flow of a program, making it behave differently in different situations.If Conditional Statement in PythonIf statement is the simplest form of a conditional sta
6 min read
Loops in Python - For, While and Nested LoopsLoops in Python are used to repeat actions efficiently. The main types are For loops (counting through items) and While loops (based on conditions). In this article, we will look at Python loops and understand their working with the help of examples. For Loop in PythonFor loops is used to iterate ov
9 min read
Python FunctionsPython Functions is a block of statements that does a specific task. The idea is to put some commonly or repeatedly done task together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over an
9 min read
Recursion in PythonRecursion involves a function calling itself directly or indirectly to solve a problem by breaking it down into simpler and more manageable parts. In Python, recursion is widely used for tasks that can be divided into identical subtasks.In Python, a recursive function is defined like any other funct
6 min read
Python Lambda FunctionsPython Lambda Functions are anonymous functions means that the function is without a name. As we already know the def keyword is used to define a normal function in Python. Similarly, the lambda keyword is used to define an anonymous function in Python. In the example, we defined a lambda function(u
6 min read
Python Data Structures
Python StringA string is a sequence of characters. Python treats anything inside quotes as a string. This includes letters, numbers, and symbols. Python has no character data type so single character is a string of length 1.Pythons = "GfG" print(s[1]) # access 2nd char s1 = s + s[0] # update print(s1) # printOut
6 min read
Python ListsIn Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Python TuplesA tuple in Python is an immutable ordered collection of elements. Tuples are similar to lists, but unlike lists, they cannot be changed after their creation (i.e., they are immutable). Tuples can hold elements of different data types. The main characteristics of tuples are being ordered , heterogene
6 min read
Dictionaries in PythonPython dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier to
7 min read
Python SetsPython set is an unordered collection of multiple items having different datatypes. In Python, sets are mutable, unindexed and do not contain duplicates. The order of elements in a set is not preserved and can change.Creating a Set in PythonIn Python, the most basic and efficient method for creating
10 min read
Python ArraysLists in Python are the most flexible and commonly used data structure for sequential storage. They are similar to arrays in other languages but with several key differences:Dynamic Typing: Python lists can hold elements of different types in the same list. We can have an integer, a string and even
9 min read
List Comprehension in PythonList comprehension is a way to create lists using a concise syntax. It allows us to generate a new list by applying an expression to each item in an existing iterable (such as a list or range). This helps us to write cleaner, more readable code compared to traditional looping techniques.For example,
4 min read
Advanced Python
Python OOPs ConceptsObject Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. OOPs is a way of organizing code that uses objects and classes to represent real-world entities and their behavior. In OOPs, object has attributes thing th
11 min read
Python Exception HandlingPython Exception Handling handles errors that occur during the execution of a program. Exception handling allows to respond to the error, instead of crashing the running program. It enables you to catch and manage errors, making your code more robust and user-friendly. Let's look at an example:Handl
6 min read
File Handling in PythonFile handling refers to the process of performing operations on a file, such as creating, opening, reading, writing and closing it through a programming interface. It involves managing the data flow between the program and the file system on the storage device, ensuring that data is handled safely a
4 min read
Python Database TutorialPython being a high-level language provides support for various databases. We can connect and run queries for a particular database using Python and without writing raw queries in the terminal or shell of that particular database, we just need to have that database installed in our system.A database
4 min read
Python MongoDB TutorialMongoDB is a popular NoSQL database designed to store and manage data flexibly and at scale. Unlike traditional relational databases that use tables and rows, MongoDB stores data as JSON-like documents using a format called BSON (Binary JSON). This document-oriented model makes it easy to handle com
2 min read
Python MySQLMySQL is a widely used open-source relational database for managing structured data. Integrating it with Python enables efficient data storage, retrieval and manipulation within applications. To work with MySQL in Python, we use MySQL Connector, a driver that enables seamless integration between the
9 min read
Python PackagesPython packages are a way to organize and structure code by grouping related modules into directories. A package is essentially a folder that contains an __init__.py file and one or more Python files (modules). This organization helps manage and reuse code effectively, especially in larger projects.
12 min read
Python ModulesPython Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work.In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we c
7 min read
Python DSA LibrariesData Structures and Algorithms (DSA) serve as the backbone for efficient problem-solving and software development. Python, known for its simplicity and versatility, offers a plethora of libraries and packages that facilitate the implementation of various DSA concepts. In this article, we'll delve in
15 min read
List of Python GUI Library and PackagesGraphical User Interfaces (GUIs) play a pivotal role in enhancing user interaction and experience. Python, known for its simplicity and versatility, has evolved into a prominent choice for building GUI applications. With the advent of Python 3, developers have been equipped with lots of tools and li
11 min read
Data Science with Python
NumPy Tutorial - Python LibraryNumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens
3 min read
Pandas TutorialPandas is an open-source software library designed for data manipulation and analysis. It provides data structures like series and DataFrames to easily clean, transform and analyze large datasets and integrates with other Python libraries, such as NumPy and Matplotlib. It offers functions for data t
6 min read
Matplotlib TutorialMatplotlib is an open-source visualization library for the Python programming language, widely used for creating static, animated and interactive plots. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, Qt, GTK and wxPython. It
5 min read
Python Seaborn TutorialSeaborn is a library mostly used for statistical plotting in Python. It is built on top of Matplotlib and provides beautiful default styles and color palettes to make statistical plots more attractive.In this tutorial, we will learn about Python Seaborn from basics to advance using a huge dataset of
15+ min read
StatsModel Library- TutorialStatsmodels is a useful Python library for doing statistics and hypothesis testing. It provides tools for fitting various statistical models, performing tests and analyzing data. It is especially used for tasks in data science ,economics and other fields where understanding data is important. It is
4 min read
Learning Model Building in Scikit-learnBuilding machine learning models from scratch can be complex and time-consuming. Scikit-learn which is an open-source Python library which helps in making machine learning more accessible. It provides a straightforward, consistent interface for a variety of tasks like classification, regression, clu
8 min read
TensorFlow TutorialTensorFlow is an open-source machine-learning framework developed by Google. It is written in Python, making it accessible and easy to understand. It is designed to build and train machine learning (ML) and deep learning models. It is highly scalable for both research and production.It supports CPUs
2 min read
PyTorch TutorialPyTorch is an open-source deep learning framework designed to simplify the process of building neural networks and machine learning models. With its dynamic computation graph, PyTorch allows developers to modify the networkâs behavior in real-time, making it an excellent choice for both beginners an
7 min read
Web Development with Python
Flask TutorialFlask is a lightweight and powerful web framework for Python. Itâs often called a "micro-framework" because it provides the essentials for web development without unnecessary complexity. Unlike Django, which comes with built-in features like authentication and an admin panel, Flask keeps things mini
8 min read
Django Tutorial | Learn Django FrameworkDjango is a Python framework that simplifies web development by handling complex tasks for you. It follows the "Don't Repeat Yourself" (DRY) principle, promoting reusable components and making development faster. With built-in features like user authentication, database connections, and CRUD operati
10 min read
Django ORM - Inserting, Updating & Deleting DataDjango's Object-Relational Mapping (ORM) is one of the key features that simplifies interaction with the database. It allows developers to define their database schema in Python classes and manage data without writing raw SQL queries. The Django ORM bridges the gap between Python objects and databas
4 min read
Templating With Jinja2 in FlaskFlask is a lightweight WSGI framework that is built on Python programming. WSGI simply means Web Server Gateway Interface. Flask is widely used as a backend to develop a fully-fledged Website. And to make a sure website, templating is very important. Flask is supported by inbuilt template support na
6 min read
Django TemplatesTemplates are the third and most important part of Django's MVT Structure. A Django template is basically an HTML file that can also include CSS and JavaScript. The Django framework uses these templates to dynamically generate web pages that users interact with. Since Django primarily handles the ba
7 min read
Python | Build a REST API using FlaskPrerequisite: Introduction to Rest API REST stands for REpresentational State Transfer and is an architectural style used in modern web development. It defines a set or rules/constraints for a web application to send and receive data. In this article, we will build a REST API in Python using the Fla
3 min read
How to Create a basic API using Django Rest Framework ?Django REST Framework (DRF) is a powerful extension of Django that helps you build APIs quickly and easily. It simplifies exposing your Django models as RESTfulAPIs, which can be consumed by frontend apps, mobile clients or other services.Before creating an API, there are three main steps to underst
4 min read
Python Practice
Python QuizThese Python quiz questions are designed to help you become more familiar with Python and test your knowledge across various topics. From Python basics to advanced concepts, these topic-specific quizzes offer a comprehensive way to practice and assess your understanding of Python concepts. These Pyt
3 min read
Python Coding Practice ProblemsThis collection of Python coding practice problems is designed to help you improve your overall programming skills in Python.The links below lead to different topic pages, each containing coding problems, and this page also includes links to quizzes. You need to log in first to write your code. Your
1 min read
Python Interview Questions and AnswersPython is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read