Search code examples
pythonpywinauto

How to use SetText for a edit box whose name has spaces in python code


I am automating an application using pywinauto. I used PrintControlIdentifiers to print object names and properties. Few of the edit boxes have space in the name. Here is one example:

| [u'Cr. PriceEdit1', u'Cr. PriceEdit0', u'Tr. PriceEdit']
   | child_window(class_name="Edit")

I cannot use parentWindow.Cr. PriceEdit1.SetText("name1") as it results in compile error. How do I use this control in code to do a SetText?

Note: I know to use child_window(title="Cr. PriceEdit0", class_name="Edit") but still want to know if there is a way where i can directly use SetText with the edit box name.


Solution

  • pywinauto can use neighbor controls for static naming of dynamic text controls like an edit box. There are 5 rules here that can be applied. In your case it should be rule #4.

    I suppose "Cr. Price" is a text inside edit box while "Tr. Price" is a static text (label) at the left side. Of course it's better to use static text everywhere because edit box content is constantly changing.

    To avoid syntax errors with incorrect attribute name you should replace not allowed symbols with underscores, for example. Or you can just remove them:

    parentWindow.Cr__PriceEdit1.SetText("name1")
    parentWindow.TrPriceEdit.SetText("name1")
    

    This should work because pywinauto uses so called "best match" algorithm to do attribute access. It calculates distance between every 2 texts and chooses the closest text or fails if all texts are too far from target one.

    Say these statement do the same:

    parentWindow.child_window(best_match='Cr__PriceEdit1').SetText("name1")
    parentWindow.child_window(best_match='TrPriceEdit').SetText("name1")
    

    Another way to do "best match" is a key based access:

    parentWindow[u'Tr. PriceEdit'].SetText('name1')
    # is the same as
    parentWindow.child_window(best_match=u'Tr. PriceEdit').SetText('name1')