Take a screenshot in python using pyautogui

To take a screenshot of the screen or a specific window in Python, you can use the Pillow library (PIL) along with pyautogui, which provides a simple way to capture screenshots.

Code

Here’s how to take a screenshot of the screen using pyautogui:

import pyautogui
from datetime import datetime

# Function to take a screenshot
def take_screenshot():
    # Capture the screenshot
    screenshot = pyautogui.screenshot()

    # Generate a filename with the current timestamp
    filename = f"screenshot_{datetime.now().strftime('%Y-%m-%d_%H-%M-%S')}.png"

    # Save the screenshot
    screenshot.save(filename)
    print(f"Screenshot saved as {filename}")

# Take the screenshot
take_screenshot()

Explanation

  1. Import Libraries:
    • pyautogui: Provides the screenshot() method to capture screenshots.
    • datetime: Used to generate a timestamped filename to save the screenshot with the current date and time.
  2. Define take_screenshot() Function:
    • This function captures a screenshot and saves it as an image file.
    • Capture the Screenshot:
      • screenshot = pyautogui.screenshot(): Calls screenshot() to take a screenshot of the entire screen and returns it as a Pillow Image object.
    • Generate a Filename:
      • filename = f”screenshot_{datetime.now().strftime(‘%Y-%m-%d_%H-%M-%S’)}.png”: Generates a filename with a timestamp using the current date and time, formatted as YYYY-MM-DD_HH-MM-SS.png.
    • Save the Screenshot:
      • screenshot.save(filename): Saves the screenshot as a PNG file with the generated filename.
      • print(…) confirms that the screenshot has been saved and provides the file name.
  3. Take the Screenshot:
    • take_screenshot() is called to capture the screenshot and save it.

How to Use

  1. Run this script, and it will take a screenshot of the entire screen.
  2. The screenshot will be saved in the same directory as the script with a filename like screenshot_2024-11-01_12-30-45.png.

Important Notes

  • Saving Path: The screenshot is saved in the same directory as the script. You can change filename to include a specific directory if you want it saved elsewhere.
  • File Format: The .png format is specified for high-quality images. You can change it to .jpg if a smaller file size is preferred.
  • Dependencies:
    • Ensure you have pyautogui and Pillow installed:
      pip install pyautogui pillow
      

Summary

This script provides a quick way to capture and save screenshots using Python.

The take_screenshot() function captures the screen and saves it with a timestamped filename, making it easy to organize multiple screenshots without overwriting previous ones.

Related posts

BMI and BMR calculator using Tkinter

A Python program that generates a random password

a Python GUI-based random quote generator