Different ways to take screenshot in python programmatically

Different ways to take screenshots in python programmatically:

If you are writing a python script that needs to take a screenshot, there are different ways to do that. But you need to use an external module for that. Python, itself doesn’t provide it. I will show you two different ways to do that using two different modules - pillow and pyautogui. Both are third party modules and you need to use pip or pip3 to install.

Method 1: Screenshot using pillow:

pillow is a popular image manipulation library. It had many useful utility methods like image compression, screenshot etc. To take a screenshot using pillow, we can use the ImageGrab class defined in it. This class provides grab() method that can be used to take a screenshot.

But, before that, you need to install pillow in your project.

pip install pillow

Now, write the below script to take the full screenshot of your system:

from PIL import ImageGrab

if __name__ == '__main__':
    screen_shot = ImageGrab.grab()

If you run this script, it will take the screenshot of the full window. Here,

  • We are using ImageGrab.grab() to take the screenshot.

We can also define the area where we want to take the screenshot. grab takes one tuple and it captures the screen based on the values in the tuple. The tuple should have 4 values. First one is the value of x, second one is the value of y, third one is the width of the screenshot and the fourth one is the height of the screenshot.

Let’s take a screenshot of 500*500 size:

from PIL import ImageGrab

if __name__ == '__main__':
    screen_shot = ImageGrab.grab((0, 0, 500, 500))

It will take screenshot of only a part of the screen. In my system, it results the below image:

python take screenshot programmatically

Method 2: By using pyautogui:

pyautogui is a GUI automation python module. We can use it to programmatically control the keyboard and mouse events.

You can install it using pip:

pip install pyautogui

Once the installation is done, you can use the below script to take a screenshot:

import pyautogui

if __name__ == '__main__':
    screen_shot = pyautogui.screenshot()

It takes the screenshot and stores it in screenshot.png file.

You might also like: