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.
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() screen_shot.save('screenshot.png')
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)) screen_shot.save('screenshot.png')
It will take screenshot of only a part of the screen. In my system, it results the below image:
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() screen_shot.save('screenshot.png')
It takes the screenshot and stores it in screenshot.png file.
- Python program to print all alphabets from A to Z in uppercase and lowercase
- Python program to reverse all strings in a list of strings
- Python program to create a list of random numbers
- Python program to concatenate a list of characters to a string
- Python numpy logical AND example
- Python program to find the IP address