Toggle labels in a map document

I had a request from the Asset Management team to display all the asset management data I had for a particular area, grouped by service category and with labels displaying their unique IDs. My challenge was to turn on the labels for all the layers using a specific expression. However, the ID fields were not named the same in all the layers (again, the joys of working with data received from outside).

# @date 17/09/2014
# @author Cindy Williams
# Set the label field and switch labels on for
# all layers in a mxd.
# For use in the Python window in ArcMap.
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.isFeatureLayer:
f = arcpy.ListFields(lyr, "*GIS*")
if f:
lyr.labelClasses[0].expression = "[" + f[0].name + "]"
lyr.showLabels = True
lyr.visible = True

On line 19, I set the label expression for the default label class using the correct field name. The square brackets are what ArcGIS is expecting to delimit field names in the label expression dialog. Line 20 turns the labels on, while line 23 turns the layer on.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.