SoFunction
Updated on 2025-03-02

Detailed explanation of how to monitor screen changes and take screenshots using Python

1. Import the required modules

First, we need to import some Python modules, including PIL (Python Imaging Library), numpy, os and time. These modules will help us take screen images and perform file and time-related operations.

from PIL import ImageGrab  # Import ImageGrab module to capture screen imagesimport numpy as np  # Import numpy module to process image dataimport os  # Import the os module for file and folder operationsimport time  # Import time module for time-related operations

2. Set the screenshot save path

Next, we will set the path to save the screenshot. In this example, we save the screenshots to a folder called "Screenshots" on the user's desktop.

desktop_path = (("~"), "Desktop")  # Get the desktop path of the current userscreenshot_folder = (desktop_path, "Screenshots")  # Set the path to save the folder by screenshot(screenshot_folder, exist_ok=True)  # Create screenshot to save the folder, ignore it if the folder already exists

3. Define the monitoring area

We need to define the upper left and lower right coordinates of the screen area to be monitored. In this example, we selected an area of ​​800x600 pixels

monitor_region = (0, 0, 800, 600)  # Example:Top left corner(0, 0),Lower right corner(800, 600)

4. Initialize the last screenshot

We will use a variable to save the previous screenshot to compare with the current screenshot to detect if the screen has changed.

last_screenshot = (bbox=monitor_region)  # Snapshot screen image in the specified area and assign value to the last_screenshot variable

5. Monitor screen changes and take screenshots

Now we will enter an infinite loop, where we continuously monitor the changes in the screen. When a screen changes are detected, we will take a screenshot and save it.

try:
    while True:  # Enter an infinite loop and continuously monitor screen changes        # Get the current screenshot        current_screenshot = (bbox=monitor_region)  # Snapshot screen image in the specified area and assign value to the current_screenshot variable
        # Convert images to NumPy array...
        # Calculate the pixel value difference in the monitoring area...
        # Check whether the pixel value difference exceeds the threshold...
        # Save screenshots...
        # Output screenshot information...
        # Updated the last screenshot...
        # Take screenshots every certain time...except KeyboardInterrupt:  # Capture keyboard interrupt exception, used to stop monitoring    print("Monitoring stopped.")  # Print the prompt message for stop monitoring

6. Complete code

from PIL import ImageGrab  # Import ImageGrab module to capture screen imagesimport numpy as np  # Import numpy module to process image dataimport os  # Import the os module for file and folder operationsimport time  # Import time module for time-related operations
# Set the screenshot save pathdesktop_path = (("~"), "Desktop")  # Get the desktop path of the current userscreenshot_folder = (desktop_path, "Screenshots")  # Set the path to save the folder by screenshot(screenshot_folder, exist_ok=True)  # Create screenshot to save the folder, ignore it if the folder already exists
# Define the upper left and lower right coordinates of the monitoring areamonitor_region = (0, 0, 800, 600)  # Example: upper left corner (0, 0), lower right corner (800, 600)
# Initialize the last screenshotlast_screenshot = (bbox=monitor_region)  # Snapshot screen image in the specified area and assign value to the last_screenshot variable
try:
    while True:  # Enter an infinite loop and continuously monitor screen changes        # Get the current screenshot        current_screenshot = (bbox=monitor_region)  # Snapshot screen image in the specified area and assign value to the current_screenshot variable
        # Convert an image to a NumPy array        current_screenshot_array = (current_screenshot)  # Convert the current screenshot to a NumPy array        last_screenshot_array = (last_screenshot)  # Convert the last screenshot to a NumPy array
        # Calculate the pixel value difference in the monitoring area        pixel_diff = (current_screenshot_array != last_screenshot_array)  # Calculate the sum of the differences between two cut-up pixels
        # Check whether the pixel value difference exceeds the threshold (adjust the threshold according to the specific situation)        threshold = 1000  # Sample threshold, adjust according to actual situation        if pixel_diff > threshold:  # If the pixel value difference exceeds the threshold, it means that the screen has changed            # Generate screenshot file name            screenshot_filename = f"screenshot_{int(())}.png"  # Generate screenshot file name based on the current time            screenshot_path = (screenshot_folder, screenshot_filename)  # Splice screenshot file path
            # Save screenshot            current_screenshot.save(screenshot_path)  # Save the current screenshot as an image file
            # Output screenshot information            print(f"Screenshot saved: {screenshot_path}")  # Print screenshot save path
            # Update the last screenshot            last_screenshot = current_screenshot  # Assign the current screenshot to the previous screenshot for the next comparison
        # Take screenshots every certain time        (5)  # Check screen changes in 5 seconds, adjust as neededexcept KeyboardInterrupt:  # Capture keyboard interrupt exception, used to stop monitoring    print("Monitoring stopped.")  # Print the prompt message for stop monitoring

The above is a detailed explanation of the method of using Python to monitor screen changes and take screenshots. For more information about Python monitoring screens, please follow my other related articles!