Python Program to Take Screenshot Easily
pyautogui.screenshot('filename.png') function to take a screenshot and save it as an image file in Python.Examples
How to Think About It
pyautogui library provides a simple function called screenshot() that captures the screen and saves it as an image file. You just call this function with the filename where you want to save the image.Algorithm
Code
import pyautogui # Take screenshot and save as 'screenshot.png' image = pyautogui.screenshot('screenshot.png') print('Screenshot saved as screenshot.png')
Dry Run
Let's trace taking a screenshot and saving it as 'screenshot.png'.
Import pyautogui
The program loads the pyautogui library to access screenshot functions.
Call screenshot()
pyautogui.screenshot('screenshot.png') captures the current screen and saves it as 'screenshot.png'.
Print confirmation
The program prints 'Screenshot saved as screenshot.png' to confirm the action.
| Step | Action | Result |
|---|---|---|
| 1 | Import pyautogui | Library ready |
| 2 | Take screenshot and save | 'screenshot.png' file created |
| 3 | Print message | Output shown on screen |
Why This Works
Step 1: Importing pyautogui
We import pyautogui because it has the screenshot() function needed to capture the screen.
Step 2: Taking the screenshot
Calling pyautogui.screenshot('filename') captures the current screen and saves it as an image file with the given name.
Step 3: Confirming the action
Printing a message helps the user know the screenshot was successfully saved.
Alternative Approaches
from PIL import ImageGrab image = ImageGrab.grab() image.save('screenshot_pil.png') print('Screenshot saved as screenshot_pil.png')
import mss with mss.mss() as sct: sct.shot(output='screenshot_mss.png') print('Screenshot saved as screenshot_mss.png')
Complexity: O(1) time, O(1) space
Time Complexity
Taking a screenshot is a single operation that does not depend on input size, so it runs in constant time.
Space Complexity
The program uses constant extra space to store the image before saving it to disk.
Which Approach is Fastest?
The mss library is generally faster than pyautogui and Pillow for screenshots, but pyautogui is simpler for beginners.
| Approach | Time | Space | Best For |
|---|---|---|---|
| pyautogui | O(1) | O(1) | Simple and easy to use |
| Pillow (ImageGrab) | O(1) | O(1) | Windows/macOS compatibility |
| mss | O(1) | O(1) | Fast and cross-platform screenshots |
pip install pyautogui before running the screenshot code.