You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux系统下如何使用Python3对指定程序进行截图?

Linux下针对特定程序的截图方案

方案一:结合窗口坐标与ImageMagick

步骤1:获取目标程序的窗口信息

Linux下可以用xdotool或wmctrl工具获取窗口的坐标和尺寸:

  • 安装工具(以Debian/Ubuntu为例,其他发行版替换为对应包管理器命令):

    • 安装xdotool:sudo apt install xdotool
    • 安装wmctrl:sudo apt install wmctrl
  • 用xdotool获取窗口ID与几何信息:

    1. 查找目标程序的窗口ID,比如针对gedit:xdotool search --onlyvisible --class gedit
    2. 获取窗口坐标和尺寸:xdotool getwindowgeometry <窗口ID>,输出会包含类似Position: 100,200(x,y坐标)和Geometry: 800x600(宽高)的信息
  • 用wmctrl获取窗口几何信息:

    1. 列出所有窗口:wmctrl -l,找到目标窗口的名称或ID
    2. 查看窗口详细几何信息:wmctrl -G -l,输出的第3-6列依次是x坐标、y坐标、宽度、高度

步骤2:用ImageMagick截图

拿到窗口信息后,直接用import命令(ImageMagick的工具)截图:

  • 直接按窗口ID截图:import -window <窗口ID> screenshot.png
  • 按坐标区域截图:import -crop <宽度>x<高度>+<x坐标>+<y坐标> screenshot.png

方案二:用Python模块直接截图

方法1:使用pyautogui

pyautogui是一个简单易用的自动化工具,支持区域截图:

  1. 安装模块:pip install pyautogui
  2. 示例代码(结合wmctrl获取窗口坐标):
import pyautogui
import subprocess

def get_window_coords(window_title):
    # 调用wmctrl获取所有窗口的几何信息
    output = subprocess.run(['wmctrl', '-G', '-l'], capture_output=True, text=True).stdout
    for line in output.splitlines():
        parts = line.split(maxsplit=4)
        if len(parts) >=5 and window_title in parts[4]:
            return (int(parts[2]), int(parts[3]), int(parts[4]), int(parts[5]))
    return None

# 替换为你的目标窗口标题(比如gedit打开的文件标题)
target_title = "Hello World - gedit"
coords = get_window_coords(target_title)
if coords:
    x, y, w, h = coords
    screenshot = pyautogui.screenshot(region=(x, y, w, h))
    screenshot.save('pyautogui_screenshot.png')
else:
    print("未找到指定窗口")

方法2:使用mss

mss是一款轻量、高性能的截图模块,适合快速捕获屏幕区域:

  1. 安装模块:pip install mss
  2. 示例代码(结合xdotool获取窗口信息):
from mss import mss
import subprocess
import re

def get_window_geom(window_class):
    # 获取目标窗口ID
    window_id = subprocess.run(
        ['xdotool', 'search', '--onlyvisible', '--class', window_class],
        capture_output=True, text=True
    ).stdout.strip()
    if not window_id:
        return None
    # 获取窗口几何信息
    geom_output = subprocess.run(
        ['xdotool', 'getwindowgeometry', window_id],
        capture_output=True, text=True
    ).stdout
    match = re.search(r'Geometry: (\d+)x(\d+)\+(\d+)\+(\d+)', geom_output)
    if match:
        return {
            'left': int(match.group(3)),
            'top': int(match.group(4)),
            'width': int(match.group(1)),
            'height': int(match.group(2))
        }
    return None

# 替换为目标程序的class名称(比如gedit的class是"gedit")
target_class = "gedit"
monitor = get_window_geom(target_class)
if monitor:
    with mss() as sct:
        img = sct.grab(monitor)
        mss.tools.to_png(img.rgb, img.size, output='mss_screenshot.png')
else:
    print("未找到指定窗口")

内容的提问来源于stack exchange,提问作者bob charliepoo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 11:12:55