2

I am trying to get a text element to input an address using the below code. It seems that the code picks up the right elements, is finding the text elements I want to change but isn't able to actually change the text element. I'm not getting any errors so I'm not sure why it's not working.

newmxd2 = arcpy.mapping.MapDocument(newmxd)
totalAddress = address + " " + street
for text in arcpy.mapping.ListLayoutElements(newmxd2, "TEXT_ELEMENT"):
    print(text.name)
    if text.name == "Address":
        test = text.text
        text.text = totalAddress
        print("Address has been changed from {0} to {1}.".format(test,totalAddress))
    if text.name == "WO":
        text.text = str(wo)
        print("Work order has been changed to {0}.".format(wo))
    else:
        print("Text and WO elements not found.")
  • What happens if you add this line after the for loop? arcpy.RefreshActiveView() – Marcelo Villa Aug 16 at 15:28
  • That doesn't seem to change the resulting map, unfortunately. I tried refreshing the view in ArcMap itself a few times too. The code picks out the correct text elements but "text.text = totalAddress" and "text.text = str(wo)" don't actually change what is inside the text box. – JackOfTales Aug 16 at 15:35
  • Are you exporting the MXD from arcpy or just looking at the MXD in ArcMap? – Marcelo Villa Aug 16 at 15:45
  • I'm running the code in Spyder outside of ArcMap and then opening the map document to see if the changes worked. – JackOfTales Aug 16 at 15:49
  • 1
    Are you saving the document using newmxd2.save()? – Marcelo Villa Aug 16 at 15:50
4

A few things to note:

  • If you are expecting the changes to be visible when you open the MXD file in ArcMap, save the MXD at the end of your script using the newmxd2.save() method.

  • If you want to export the map (e.g. PNG of PDF) and want to see the changes in the exported file, you don't need to save the MXD as you are only using it as a template.

  • If you are experimenting in ArcMap and want to see the changes right there without the need to run the script in Spyder and then open the document you can use the Python console that comes with ArcMap. However, instead of passing a string with the path of the MXD to the arcpy.mapping.MapDocument() function, pass the string CURRENT like this: newmxd2 = arcpy.mapping.MapDocument('CURRENT'). Then, after doing your changes, run arcpy.RefreshActiveView() and see the changes you just made.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.