Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Keyboard module in Python
Next article icon

Mouse and keyboard automation using Python

Last Updated : 21 Jan, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

This article illustrates how to automate movements of mouse and keyboard using pyautogui module in python. This module is not preloaded with python. So to install it run the following command: 
 

 pip3 install pyautogui

 

Controlling mouse movements using pyautogui module

Python tracks and controls mouse using the coordinate system of the screen. Suppose the resolution of your screen is 1920X1080, then your screen’s coordinate system looks like this: 
 

gui in python

 

  • size(): This function is used to get Screen resolution.
     

Python




import pyautogui
print(pyautogui.size())
 
 

Save this file with .py extension, and then run the file. 
This python code use size() function to output your screen resolution in x, y format: 
Output: 
 

 (1920, 1080)

Note: Some of the codes provided in this article might not run on geeksforgeeks IDE, since geeksforgeeks IDE doesn’t have the required modules to run these codes. But these codes can be easily run locally on your PC by installing python and following the instructions provided in the article. 
 

  • moveTo(): use this function to move the mouse in pyautogui module. 
     

Python




import pyautogui
pyautogui.moveTo(100, 100, duration = 1)
 
 

This code uses moveTo() function, which takes x and y coordinates, and an optional duration argument. This function moves your mouse pointer from it’s current location to x, y coordinate, and takes time as specified by duration argument to do so. Save and run this python script to see your mouse pointer magically moving from its current location to coordinates (100, 100), taking 1 second in this process. 
 

  • moveRel() function: moves the mouse pointer relative to its previous position. 
     

Python




import pyautogui
pyautogui.moveRel(0, 50, duration = 1)
 
 

This code will move mouse pointer at (0, 50) relative to its original position. For example, if mouse position before running the code was (1000, 1000), then this code will move the pointer to coordinates (1000, 1050) in duration 1 second. 
 

  • position(): function to get current position of the mouse pointer. 
     

Python




import pyautogui
print(pyautogui.position())
 
 

Output: coordinates where your mouse was residing at the time of executing the program. 
 

  • click(): Function used for clicking and dragging the mouse. 
     

Python




import pyautogui
pyautogui.click(100, 100)
 
 

This code performs a typical mouse click at the location (100, 100). 
We have two functions associated with the drag operation of the mouse, dragTo and dragRel. They perform similar to moveTo and moveRel functions, except they hold the left mouse button while moving, thus initiating a drag. 
This functionality can be used at various places, like moving a dialog box, or drawing something automatically using a pencil tool in MS Paint. To draw a square in paint: 
 

Python




import time
 
# a module which has functions related to time.
# It can be installed using cmd command:
# pip install time, in the same way as pyautogui.
import pyautogui
time.sleep(10)
 
# makes program execution pause for 10 sec
pyautogui.moveTo(1000, 1000, duration = 1)
 
# moves mouse to 1000, 1000.
pyautogui.dragRel(100, 0, duration = 1)
 
# drags mouse 100, 0 relative to its previous position,
# thus dragging it to 1100, 1000
pyautogui.dragRel(0, 100, duration = 1)
pyautogui.dragRel(-100, 0, duration = 1)
pyautogui.dragRel(0, -100, duration = 1)
 
 

Before running the code, open MS paint in the background with the pencil tool selected. Now run the code, quickly switch to MS paint before 10 seconds (since we have given 10 second pause time using sleep() function before running the program). 
After 10 seconds, you will see a square being drawn in MS paint, with its top-left edge at 1000, 1000, and edge length 100 pixels.

  • scroll(): scroll function takes no. of pixels as an argument, and scrolls the screen up to a given number of pixels.
     

Python




import pyautogui
pyautogui.scroll(200)
 
 

This code scrolls the active screen up to 200 pixels. 
 

  • typewrite(): You can automate typing of the string by using typewrite() function. just pass the string which you want to type as an argument of this function. 
     

Python




import pyautogui
pyautogui.click(100, 100)
pyautogui.typewrite("hello Geeks !")
 
 

Suppose a text field was present at coordinates 100, 100 on-screen, then this code will click the text field to make it active and type “hello Geeks!” in it. 
 

  • Passing key names: You can pass key names separately through typewrite() function. 
     

Python




import pyautogui
pyautogui.typewrite(["a", "left", "ctrlleft"])
 
 

This code is the automatic equivalent of typing “a”, pressing the left arrow key, and pressing the left control key. 
 

  • Pressing hotkey combinations: Use hotkey() function to press the combination of keys like ctrl-c, ctrl-a, etc.
     

Python




import pyautogui
pyautogui.hotkey("ctrlleft", "a")
 
 

This code is the automatic equivalent of pressing left ctrl and “a” simultaneously. Thus in windows, this will result in the selection of all text present on the screen.

Example:

To send a message in WhatsApp and delete it for everyone automatically. You need to have Whatsapp already opened in chrome, to run this. After running this code, open the WhatsApp tab on chrome.

Python3




import pyautogui as pg
import time
 
def delete_for_everyone():
    pg.click(807, 979)
    pg.typewrite("hello")
    pg.typewrite(["enter"])
    time.sleep(2)
    pg.click(1621, 896)
    pg.click(1621, 896)
     
    # time.sleep(1)
    pg.click(1693, 859)
     
    # time.sleep(1)
    pg.click(1014, 669)
     
    # time.sleep(1)
    pg.click(1111, 605)
     
a=20
time.sleep(10)
while(a!=0):
    delete_for_everyone()
    a=a-1
 
 

 



Next Article
Keyboard module in Python

T

tkkhhaarree
Improve
Article Tags :
  • Python
Practice Tags :
  • python

Similar Reads

  • GUI Automation using Python
    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 mou
    12 min read
  • Keyboard module in Python
    Python provides a library named keyboard which is used to get full control of the keyboard. It's a small Python library which can hook global events, register hotkeys, simulate key presses and much more. It helps to enter keys, record the keyboard activities and block the keys until a specified key
    2 min read
  • Best Python Modules for Automation
    Automation is an addition of technology that performs tasks with reduced human assistance to processes that facilitate feedback loops between operations and development teams so that iterative updates can be deployed faster to applications in production. There are different types of automation libra
    3 min read
  • Virtual Keyboard in python using OpenCv
    Virtual keyboards are becoming a necessary tool for many applications, particularly those using touchscreens and augmented reality. Hand gestures combined with a virtual keyboard may provide for an intuitive and engaging user interface. This post will demonstrate how to use OpenCV, a powerful packag
    6 min read
  • How To Automate Google Chrome Using Foxtrot and Python
    In this article, we are going to see how to automate google chrome using Foxtrot & Python. What is Foxtrot RPA?Robotic process automation (RPA) cuts down employees’ workloads by automating repetitive, high-volume steps in processes. Software robots, such as Foxtrot RPA emulate the actions of hum
    4 min read
  • Google Maps Selenium automation using Python
    Prerequisites: Browser Automation using Selenium Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS, and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. It can
    4 min read
  • Browser Automation Using Selenium
    Selenium is a powerful tool for controlling a web browser through the program. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e Python, Java, C#, etc, we will be working with Python. Mastering Selenium will help you automate your day to da
    3 min read
  • Keyboard buttons in Telegram bot Using Python
    One common way that we interact with the Telegram bot is through the use of keyboard buttons. These buttons give a convenient and intuitive way to input data and perform specific actions within the bot. Without keyboard buttons, we would have to manually type in commands or responses, which could be
    9 min read
  • Python Automation Tutorial: Beginner to Advanced
    Python is a very powerful programming language and it's expanding quickly because of its ease of use and straightforward syntax. In this Python Automation Tutorial, we will explore various techniques and libraries in Python to automate repetitive tasks.  Automation can save you time and reduce error
    10 min read
  • PYGLET – Mouse Button String
    In this article we will see how we can mouse button string in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as f
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences