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

Ubuntu 22.04 Wayland环境下pyautogui截图黑屏的替代方案求助

Wayland环境下替代pyautogui截图的方案(Ubuntu 22.04)

pyautogui的截图功能在Wayland环境下因兼容性问题会出现黑屏,以下是几个无需切换到Xorg的替代方案:

方案1:使用mss库

mss是专门针对截图优化的库,对Wayland有良好支持,无需额外权限配置。

安装

pip install mss

替代代码

from mss import mss

x1, y1 = 1525, 312
x2, y2 = 1655, 370
# mss的区域参数为 (left, top, width, height),需转换坐标
region = {
    "left": x1,
    "top": y1,
    "width": x2 - x1,
    "height": y2 - y1
}

with mss() as sct:
    # 截取指定区域
    screenshot = sct.grab(region)
    # 保存为PNG
    mss.tools.to_png(screenshot.rgb, screenshot.size, output="test.png")

方案2:调用系统截图工具(gnome-screenshot)

利用Ubuntu默认的gnome-screenshot工具(Wayland兼容),先截取全屏再裁剪目标区域。

代码示例

import subprocess
from PIL import Image
import os

x1, y1 = 1525, 312
x2, y2 = 1655, 370

# 截取全屏
subprocess.run(["gnome-screenshot", "-f", "_temp_full.png"], check=True)

# 裁剪指定区域
with Image.open("_temp_full.png") as img:
    cropped_img = img.crop((x1, y1, x2, y2))
    cropped_img.save("test.png")

# 删除临时全屏截图
os.remove("_temp_full.png")

注意:若使用其他Wayland桌面环境,需替换为对应截图工具(如KDE的spectacle)。

方案3:使用PyGObject调用GTK原生API

通过GTK的Gdk库直接获取屏幕像素,完全适配Wayland环境,属于原生系统级调用。

安装依赖

sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0

代码示例

from gi.repository import Gdk
from PIL import Image

x1, y1 = 1525, 312
x2, y2 = 1655, 370
width = x2 - x1
height = y2 - y1

# 获取当前显示和根窗口
display = Gdk.Display.get_default()
root_window = display.get_default_screen().get_root_window()

# 截取指定区域的像素缓冲区
pixbuf = Gdk.pixbuf_get_from_window(root_window, x1, y1, width, height)

# 转换为PIL Image并保存
img = Image.frombytes("RGB", (width, height), pixbuf.get_pixels())
img.save("test.png")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 09:40:42