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

如何使用Python Xlib获取窗口图标并保存为PNG格式?

解决窗口图标获取返回None的问题

1. 给代码加属性存在性检查+多尺寸图标适配

你的代码直接访问.value,但如果目标窗口没有_NET_WM_ICON属性,get_full_property会返回None,直接调用会报错。同时_NET_WM_ICON本身是多尺寸图标数组,需要遍历找到你要的16x16规格,修改后的代码如下:

from Xlib.display import Display
from Xlib import X
from PIL import Image

def getIcon(window, display):
    # 先获取属性,检查是否存在
    icon_prop = window.get_full_property(
        display.intern_atom('_NET_WM_ICON'),
        X.AnyPropertyType
    )
    if not icon_prop or not icon_prop.value:
        # 属性不存在时,调用降级方案获取图标
        return get_fallback_icon(window, display)
    
    icon_data = icon_prop.value
    offset = 0
    data_length = len(icon_data)
    # 遍历所有图标,找16x16的规格
    while offset < data_length:
        width = icon_data[offset]
        height = icon_data[offset + 1]
        # 找到目标尺寸就生成图像返回
        if width == 16 and height == 16:
            pixel_start = offset + 2
            pixel_end = pixel_start + width * height * 4
            pixel_data = icon_data[pixel_start:pixel_end]
            return Image.frombytes(
                'RGBA', (width, height), bytes(pixel_data), 'raw', 'BGRA'
            )
        # 计算下一个图标的起始偏移
        offset += 2 + width * height * 4
    
    # 没有16x16的话,取第一个可用图标
    width = icon_data[0]
    height = icon_data[1]
    pixel_data = icon_data[2:2 + width*height*4]
    return Image.frombytes(
        'RGBA', (width, height), bytes(pixel_data), 'raw', 'BGRA'
    )

def get_fallback_icon(window, display):
    # 降级到X11传统的WM_HINTS图标属性
    wm_hints = window.get_wm_hints()
    if wm_hints and wm_hints.icon_pixmap:
        pixmap = wm_hints.icon_pixmap
        geom = pixmap.get_geometry()
        # 从pixmap提取图像数据,适配ZPixmap格式
        img_data = pixmap.get_image(0, 0, geom.width, geom.height, X.ZPixmap, 0xffffffff)
        return Image.frombytes('RGB', (geom.width, geom.height), img_data.data, 'raw', 'BGRX')
    # 所有方案都失败,返回None或自定义默认图标
    return None

2. 为什么会出现返回None的情况?

  • 不是所有X11窗口都实现了_NET_WM_ICON属性,比如部分老旧程序、极简工具窗口
  • 有些窗口只提供大尺寸图标,没有16x16规格的
  • 窗口可能还未完成初始化,_NET_WM_ICON属性尚未被设置

3. 额外注意点

  • _NET_WM_ICON的格式是多图标数组:每个图标以width、height两个整数开头,后面跟着width*height*4个整数(对应每个像素的BGRA四字节数据)
  • 当_NET_WM_ICON不可用时,必须通过WM_HINTS的icon_pixmap做降级处理,这是X11的标准 fallback 方案
  • 从pixmap提取图像时,要注意和当前屏幕的颜色深度匹配,不同环境可能需要调整get_image的参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:53:18