【问题标题】:pywinauto: Iterate through all controls in a windowpywinauto:遍历窗口中的所有控件
【发布时间】:2018-08-30 11:39:37
【问题描述】:

我正在尝试编写一个通用测试脚本来查找新软件版本中的错误。我的想法是遍历窗口中的控件并与每个控件进行交互,记录导致的任何错误并在软件崩溃时重新启动软件。

我正在寻找一种动态查找控件标识符的方法,有点像print_control_identifiers(),但输出是一个列表或类似的结构,我可以遍历它。

GitHub question 关于控件标识符的文章中提到了这一点:

可以使用.children()(仅限直接子级)和.descendants() (整个子树作为普通列表)来遍历层次结构

我以为我可以遍历我的Application 对象的descendants() 列表并为每个对象调用一个相关的交互方法,但是我不知道如何获取这个列表。我以为我可以做这样的事情,但我没有成功:

def test(application):
    for child in application.descendants():
        #interact with child control

software = Application(backend='uia').start(cmd_line=FILE_PATH)
test(software)

AttributeError: GUI 元素(包装器)和包装器方法“后代”均未找到(错字?)


编辑


我求助于查看the code 并找到了print_control_identifiers 方法:

class Application(object):

    def print_control_identifiers(self, depth=None, filename=None):
        """
        Prints the 'identifiers'
        Prints identifiers for the control and for its descendants to
        a depth of **depth** (the whole subtree if **None**).
        .. note:: The identifiers printed by this method have been made
               unique. So if you have 2 edit boxes, they won't both have "Edit"
               listed in their identifiers. In fact the first one can be
               referred to as "Edit", "Edit0", "Edit1" and the 2nd should be
               referred to as "Edit2".
        """
        if depth is None:
            depth = sys.maxsize
        # Wrap this control
        this_ctrl = self.__resolve_control(self.criteria)[-1]

        # Create a list of this control and all its descendants
        all_ctrls = [this_ctrl, ] + this_ctrl.descendants()

        # Create a list of all visible text controls
        txt_ctrls = [ctrl for ctrl in all_ctrls if ctrl.can_be_label and ctrl.is_visible() and ctrl.window_text()]

        # Build a dictionary of disambiguated list of control names
        name_ctrl_id_map = findbestmatch.UniqueDict()
        for index, ctrl in enumerate(all_ctrls):
            ctrl_names = findbestmatch.get_control_names(ctrl, all_ctrls, txt_ctrls)
            for name in ctrl_names:
                name_ctrl_id_map[name] = index

        # Swap it around so that we are mapped off the control indices
        ctrl_id_name_map = {}
        for name, index in name_ctrl_id_map.items():
            ctrl_id_name_map.setdefault(index, []).append(name)

这说明.descendants()不是Application类的方法,而是属于控件。看来我错了。是否可以创建我自己的print_control-identifiers() 版本,它返回可以迭代的控制对象列表?

【问题讨论】:

    标签: python pywinauto


    【解决方案1】:

    列出顶级窗口的正确方法是application.windows()。然后您可以为每个列出的窗口调用.descendants()。在大多数情况下,应用程序只有一个顶级窗口。特别是对于backend="uia",甚至新对话框都是主窗口的子窗口(对于backend="win32",每个对话框都是顶级窗口)。

    【讨论】:

    • 这成功了!我使用嵌套的 for 循环遍历每个窗口的所有后代并打印它们。再次感谢
    猜你喜欢
    • 2012-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多