How to Take a Screenshot using Python

In this article we will see how to take screenshot using python with the help of pyautogui python package which is used for cross-platform GUI automation, programmatically control the mouse and keyboard.

Install the pyautogui package

Can install the pyautogui package using the following command on windows, mac and linux.

1pip install pyautogui

On Linux, additionally you will need to install the scrot application, as well as Tkinter

sudo apt-get install scrot

sudo apt-get install python3-tk

sudo apt-get install python3-dev

Take the screenshot using Python

To take screenshot first import the pyautogui module, then call the screenshot method and save the file as a png format in current working folder.

1import pyautogui 2 3screenshot = pyautogui.screenshot() 4screenshot.save("my_screenshot.png")

Save screenshot in different folder

New screenshot image will be save in desktop under Image folder

1import pyautogui 2 3screenshot = pyautogui.screenshot() 4screenshot.save(r"C:\Users\Dan\Desktop\Image\my_screenshot.png")

Take screenshot of a particular region of the screen

1import pyautogui 2 3# take a square image screenshot of size 400 pixel in x and y axis 4screenshot = pyautogui.screenshot(region=(0,0, 400, 400)) 5screenshot.save(r"C:\Users\Dan\Desktop\Image\my_screenshot_region.png")