Search code examples
pythonpython-3.xpywinauto

Pywinauto: how the `findbestmatch` module works?


I'm trying to understand how the findbestmatch module works. Here is an example.

from pywinauto.application import Application
from pywinauto.findbestmatch import find_best_match
ditto=Application().connect(path='Ditto.exe').window(title="Ditto",class_name="QPasteClass")
ditto.ditto.ListView.findbestmatch.find_best_match(hello)

I'm trying to use one of its method to get the HELLO 2 items listed inside ListView. (These items don't have their own controls identifiers)

print(ditto.print_control_identifiers()) gives that:

Control Identifiers:
QPasteClass - 'Ditto'    (L1114, T321, R1366, B740)
['QPasteClass', 'DittoQPasteClass', 'Ditto']
child_window(title="Ditto", class_name="QPasteClass")
   |
   | ListView - ''    (L1116, T343, R1357, B722)
   | ['ListView<noautodelete><ingroup><pasted>|HELLO 1\n','ListView<noautodelete><ingroup><pasted>|Hello 2\n', 'ListView<noautodelete><ingroup><pasted>|Hello 3\n', ]
   | child_window(class_name="SysListView32")
   |    |
   |    | Header - ''    (L1116, T343, R1357, B343)
   |    | ['Header', 'TagsHeader']
   |    | child_window(class_name="SysHeader32")
   |
   | Header - ''    (L1116, T343, R1357, B343)
   | ['Header', 'TagsHeader']
   | child_window(class_name="SysHeader32")

I tried ditto.ListView.findbestmatch.find_best_match("HELLO 2") and many others which did not work.


Solution

  • findbestmatch is a very low level module so usually it's used implicitly when calling attribute access (say app.Ditto and app.window(best_match='Ditto') are equivalent). But in your case using findbestmatch explicitly is necessary. Here is an example:

    from pywinauto import findbestmatch
    texts = ditto.ditto.ListView.texts()[1:] # skip window text itself, use only item texts
    items = ditto.ditto.ListView.items()
    
    found_item = findbestmatch.find_best_match('pasted', texts, items)
    print(found_item)