【问题标题】:Get window position and size in python with Xlib使用 Xlib 在 python 中获取窗口位置和大小
【发布时间】:2012-10-08 04:00:01
【问题描述】:

我需要找到窗口的位置和大小,但我不知道怎么做。例如,如果我尝试:

id.get_geometry()    # "id" is Xlib.display.Window

我得到这样的东西:

data = {'height': 2540,
'width': 1440,
'depth': 24,
'y': 0, 'x': 0,
'border_width': 0
'root': <Xlib.display.Window 0x0000026a>
'sequence_number': 63}

我需要找到窗口位置和大小,所以我的问题是:“y”、“x”和“border_width”总是0;更糟糕的是,“高度”和“宽度”在没有窗口框架的情况下返回。

在本例中,在我的 X 屏幕上(其尺寸为 4400x2560),我预计 x=1280, y=0, width=1440, height=2560。

换句话说,我正在寻找 python 等价物:

#!/bin/bash
id=$1
wmiface framePosition $id
wmiface frameSize $id

如果您认为 Xlib 不是我想要的,请随意在 python 中提供非 Xlib 解决方案,如果它可以将窗口 id 作为参数(如上面的 bash 脚本)。在 python 代码中使用 bash 脚本的输出的明显解决方法感觉不对。

【问题讨论】:

标签: python xlib


【解决方案1】:

您可能正在使用重父窗口管理器,并且由于此 id 窗口的 x 和 y 为零。检查父窗口的坐标(即窗口管理器框架)

【讨论】:

  • 我使用 KWin 作为我的窗口管理器。但是如何获取父窗口?
  • 在我问如何找到父窗口之前,我搜索了一下,看到了这个页面。不幸的是,它是关于 C xlib(不是 python xlib),所以它没有帮助。知道如何用 python 找到父窗口吗?
  • parent = id.query_tree().parent
  • 非常感谢您的帮助!以下行允许我获取框架几何:“id.query_tree().parent.query_tree().parent.get_geometry()”。 WM 框架是客户端窗口的祖父母(至少在 KWin 中)。
  • 我建议独立于 wm 走到根并计算每一步的相对 x,y
【解决方案2】:

Liss 发布以下解决方案as a comment

from ewmh import EWMH
ewmh = EWMH()

def frame(client):
    frame = client
    while frame.query_tree().parent != ewmh.root:
        frame = frame.query_tree().parent
    return frame

for client in ewmh.getClientList():
    print frame(client).get_geometry()

我在这里复制它是因为answers should contain the actual answer,并防止link rot

【讨论】:

  • 所以frame() 只是返回传入客户端的第二根祖先?我不认为这完成了将树走到根并计算每一步的 x,y 的建议......
【解决方案3】:

这是我想出的似乎效果很好的方法:

from collections import namedtuple

import Xlib.display


disp = Xlib.display.Display()
root = disp.screen().root

MyGeom = namedtuple('MyGeom', 'x y height width')


def get_absolute_geometry(win):
    """
    Returns the (x, y, height, width) of a window relative to the top-left
    of the screen.
    """
    geom = win.get_geometry()
    (x, y) = (geom.x, geom.y)
    while True:
        parent = win.query_tree().parent
        pgeom = parent.get_geometry()
        x += pgeom.x
        y += pgeom.y
        if parent.id == root.id:
            break
        win = parent
    return MyGeom(x, y, geom.height, geom.width)

完整示例here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2019-12-24
    相关资源
    最近更新 更多