[GIS] Customizing label features using arcpy

arcgis-10.0arcpylabelingsymbology

I have a script that creates symbology for a polyline (contours) and then adds it to a .mxd file. My problem is that it picks the “FontName” as the default field to label on the map (see attached image) and I want to change it to a different field within the attribute table (“TextString”). I’ve looked at the labelclass object for use in arcpy, and tried to use the script below, but first of all, I’m not even sure the layer I am trying to do this with is supported (it’s a File Geodatabase Feature Class) because whenever I run the script, nothing happens (it runs b/c I get “script…returned exit code 0” at the bottom of the PythonWin window.) Does this mean that the layer is not supported and if so, would it be supported if I pull it out of the .gdb? Any help would be greatly appreciated.

import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\Project\Project.mxd")
for lyr in arcpy.mapping.ListLayers(mxd):
    if lyr.supports("LABELCLASSES"):
        if lyr.showLabels:
            print "Layer name: " + lyr.name
            for lblClass in lyr.labelClasses:
                if lblClass.showClassLabels:
                    print "    Class Name:  " + lblClass.className
                    print "    Expression:  " + lblClass.expression
                    print "    SQL Query:   " + lblClass.SQLQuery

labelimage

Best Answer

I had the same problem, wanting to use a specific field in an FC to use as the label. Here was my solution. I have a script before this that brings in a layer to the current .mxd from the disc and then this will turn the label on and use the "label" field instead of the "Loc_name" (or whatever the default label is)

import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT") 
layer = arcpy.mapping.ListLayers(mxd, "")[0] 
if layer.supports("LABELCLASSES"):
    for lblclass in layer.labelClasses:
        lblclass.showClassLabels = True
lblclass.expression = " [Label]"
layer.showLabels = True
arcpy.RefreshActiveView()