How to Get a Windows Screenshot in Python?

Problem Formulation

Say, you run a Python program on your Windows machine and you want it to take a screenshot. How to accomplish this programmatically?

Method 1: Multiple Screen Shots Module

To programmatically record one or more screenshots in your Python program, run the sct.shot() function from the mss module.

  • Install the Multiple Screen Shots (MSS) module, e.g., by running pip install mss in your Powershell or command line.
  • Import the mss() function from the mss module using the Python statement: from mss import mss
  • Open a with environment using the Python statement: with mss() as sct: ...
  • Call the shot() function on the sct environment using sct.shot()
from mss import mss

with mss() as sct:

If I run this on my Windows machine, it’ll create a file "monitor-1.png" in the directory of the Python code file. Here’s how the screenshot file looks for me:

Figure: Auto-generated screenshot file on my Windows machine.

As you see from the last error message, the mss module is not included in the standard library, so make sure to install it using pip or any other means to add the module to your environment.

You can find further examples on how to use the module here, for example if you need to customize the file path or create multiple screenshots.

Method 2: PIL.ImageGrab.grab()

A simple way to record screenshots on your Windows machine is to use the PIL module that is already installed in many environments.

  • Install PIL
  • Import ImageGrab module using the Python statement: import PIL.ImageGrab
  • Create the screenshot and store it in a variable like so: screenshot = PIL.ImageGrab.grab()
  • Display the screenshot on your Windows machine:

Here’s the simple 3-liner code:

import PIL.ImageGrab

screenshot = PIL.ImageGrab.grab()

And here’s the screenshot popping up as a new window on my machine:

If you want to store the screenshot in a specific file location rather than displaying it with your standard image viewing program, use the following approach with

from PIL import ImageGrab
screenshot = ImageGrab.grab()
path = "C:\\Users\\MyUser\\Desktop\\MyScreenshot.jpg"

Method 3: PyAutoGUI

Famous Python developer Al Sweighart has created a powerful library PyAutoGUI to control the mouse and keyboard and automate interactions with other applications. This approach works for Windows, macOS, and Linux, and Python 2 and 3. It also provides a function pyautogui.screenshot(path) that stores a screenshot at a given path location on your computer.

To install PyAutoGUI, run pip install pyautogui. Then run the following two-liner:

import pyautogui
screenshot = pyautogui.screenshot('filename.png')

This is a Pythonic, simple, and concise way to create a screenshot in Python.