杰瑞科技汇

Python如何实现屏幕截图?

Of course! Taking a screenshot in Python is a common task, and there are several excellent libraries to choose from, depending on your needs (cross-platform, GUI framework, simplicity, etc.).

Here's a comprehensive guide covering the most popular methods.

Summary: Which Method Should I Use?

Method Best For Platform Dependencies
Pillow Most users. Easy, cross-platform, saving to files. Windows, macOS, Linux Pillow
pyautogui Automation. Simple, cross-platform, good for scripts. Windows, macOS, Linux pyautogui
mss Performance. Extremely fast, ideal for games or video. Windows, macOS, Linux mss
Tkinter Simple GUI apps. No extra install needed if you have Python. Cross-platform Built-in
PyQt/PySide Complex GUI apps. Cross-platform PyQt6 / PySide6

Method 1: The Easiest & Most Popular (Pillow)

Pillow is the de-facto standard for image manipulation in Python. Its ImageGrab module is perfect for taking screenshots.

Installation

First, you need to install the library:

pip install Pillow

Basic Code: Screenshot the Entire Screen

This code captures the entire primary monitor and saves it as a screenshot.png file.

import PIL.ImageGrab
# Take a screenshot of the entire screen
screenshot = PIL.ImageGrab.grab()
# Save the screenshot to a file
screenshot.save("screenshot.png")
print("Screenshot saved as screenshot.png")

Advanced Code: Screenshot a Specific Region

You can also capture a specific area by providing a bounding box (left, top, right, bottom).

import PIL.ImageGrab
# Define the region to capture (left, top, right, bottom)
# This example captures a 400x300 pixel area starting at (100, 50)
region = (100, 50, 100 + 400, 50 + 300)
# Take a screenshot of the specified region
screenshot_region = PIL.ImageGrab.grab(region)
# Save the region screenshot
screenshot_region.save("screenshot_region.png")
print("Screenshot of region saved as screenshot_region.png")

Method 2: Great for Automation (pyautogui)

pyautogui is a powerful library for automating GUI tasks. Screenshotting is one of its many features.

Installation

pip install pyautogui

Basic Code: Screenshot the Entire Screen

import pyautogui
# Take a screenshot and get the image data as a Pillow Image object
screenshot = pyautogui.screenshot()
# Save the screenshot to a file
screenshot.save("pyautogui_screenshot.png")
print("Screenshot saved as pyautogui_screenshot.png")

Advanced Code: Screenshot a Specific Region

pyautogui makes it very easy to specify a region.

import pyautogui
# Define the region (left, top, width, height)
region = (100, 50, 400, 300)
# Take a screenshot of the region
screenshot_region = pyautogui.screenshot(region=region)
# Save the region screenshot
screenshot_region.save("pyautogui_region.png")
print("Screenshot of region saved as pyautogui_region.png")

Method 3: The Fastest Option (mss)

mss (Multi-Screen Shot) is written in C and is significantly faster than Pillow or pyautogui. It's the best choice if you need to take many screenshots in quick succession, like for recording a game or monitoring a screen.

Installation

pip install mss

Basic Code: Screenshot the Entire Screen

mss returns the image data as a raw bytes object, which you can then save or process.

import mss
import mss.tools
with mss.mss() as sct:
    # The screen part to capture
    monitor = {"top": 40, "left": 0, "width": 800, "height": 640}
    # Grab the data
    sct_img = sct.grab(monitor)
    # Save to the picture file
    mss.tools.to_png(sct_img.rgb, sct_img.size, output="mss_screenshot.png")
    print("Screenshot saved as mss_screenshot.png")

Method 4: Using Built-in Libraries (Tkinter)

If you're building a simple GUI application with Tkinter, you can take a screenshot without installing any external packages. This method captures the entire virtual screen, including all monitors.

import tkinter as tk
from PIL import ImageGrab
def capture_screenshot():
    # Get the coordinates of the entire screen
    x0 = window.winfo_rootx()
    y0 = window.winfo_rooty()
    x1 = x0 + window.winfo_width()
    y1 = y0 + window.winfo_height()
    # Take the screenshot
    screenshot = ImageGrab.grab(bbox=(x0, y0, x1, y1))
    screenshot.save("tkinter_screenshot.png")
    print("Screenshot saved as tkinter_screenshot.png")
# Create a simple Tkinter window
window = tk.Tk()
window.title("Screenshot Taker")
window.geometry("200x100")
button = tk.Button(window, text="Take Screenshot", command=capture_screenshot)
button.pack(pady=20)
window.mainloop()

Method 5: For GUI Applications (PyQt6 / PySide6)

If you are already using a Qt-based framework like PyQt or PySide, you can use its built-in functionality. This is useful for capturing a specific widget or the main window.

Installation

pip install PyQt6
# or
pip install PySide6

Code: Capture the Main Window

This example captures the content of the Qt application window itself.

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QLabel, QVBoxLayout, QWidget
from PyQt6.QtGui import QPixmap, QPainter
from PyQt6.QtCore import Qt
class ScreenshotWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt Screenshot Example")
        self.setGeometry(100, 100, 400, 300)
        # A simple label to display the screenshot
        self.label = QLabel("Click the button to take a screenshot of this window.")
        self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        button = QPushButton("Take Screenshot")
        button.clicked.connect(self.take_screenshot)
        layout = QVBoxLayout()
        layout.addWidget(self.label)
        layout.addWidget(button)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
    def take_screenshot(self):
        # Create a pixmap to hold the screenshot
        pixmap = QPixmap(self.size())
        # Render the window onto the pixmap
        self.render(pixmap)
        # Save the pixmap to a file
        pixmap.save("pyqt_window_screenshot.png")
        print("Screenshot of the window saved as pyqt_window_screenshot.png")
        self.label.setPixmap(pixmap.scaled(300, 200, Qt.AspectRatioMode.KeepAspectRatio))
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ScreenshotWindow()
    window.show()
    sys.exit(app.exec())
分享:
扫描分享到社交APP
上一篇
下一篇