Search code examples
pythonautomationui-automationpywinautooffice-automation

How do I select a particular edit controller from Microsoft Office dialog box using Pywinauto and Python


I am trying to create a Python script that will automatically fill the Journal Article details in "Create Source" dialog box of Microsoft Word with the provided data.

Basically, I want to fill the Input boxes programatically with variables containing the appropriate data for "Author", "Title" "Journal Name", "Year" etc.

I want to fill these marked boxes programatically with variables

I am trying to select these boxes by using Pywinauto. I have successfully connected Microsoft Word and Selected the "Create Source" dialg box using the following code:

app = Application(backend='uia').connect(title='Document1 - Word')

createSource = app.Document1Word.window(title='Create Source').print_control_identifiers()

The snippet from the Control Identifiers from the above code"

   | Edit - ''    (L1278, T511, R1669, B525)
   | ['EditorEdit', 'Edit10', 'EditorEdit0', 'EditorEdit1']
   | child_window(auto_id="86", control_type="Edit")
   | 
   | Edit - ''    (L1278, T534, R1753, B548)
   | ['PublisherEdit', 'Edit11', 'PublisherEdit0', 'PublisherEdit1']
   | child_window(auto_id="93", control_type="Edit")
   | 
   | Edit - ''    (L1228, T563, R1763, B574)
   | ['VolumeEdit', 'Edit12', 'VolumeEdit0', 'VolumeEdit1']
   | child_window(auto_id="96", control_type="Edit")

Now lets say, if I target the "publisher" using child_window(auto_id="93", control_type="Edit"). It works fine for the first time. But the problem is that these auto_ids change each time the program, or even the dialog box, restarts. For example, now the auto_id="93" for the "Publisher" editbox (Input Box), next time it may be, say, 57 or anything arbitratory. This breaks the whole script.

What I am doing:

app = Application(backend='uia').connect(title='Document1 - Word')
createSource = app.Document1Word.window(title='Create Source')
EditPublisherName = createSource.child_window(auto_id="93", control_type="Edit").wrapper_object()
EditPublisherName.set_edit_text("XYZ Publishers")

Again, for the first time above code, works perfectly fine. It fills the "Publisher" edit box with "XYZ Publisher" string. However this script would fail to work if I restart the dialog box. And when I run the .print_control_identifiers() after restarting the program or dialog box, all the auto_ids would have been changed. Is there a better way to target these edit boxes?

Code fills the publisher edit box


Solution

  • I assume, the alias Name doesn't change from one run to another runs. If so we can do something like this.

    set_text=app.DialogName["PublisherEdit"].type_keys("XYZ Publishers")
    

    Need to try something like this