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

Answer
The layer can be a feature class in a File Geodatabase or a shapefile. The issue with the code is that it has a if statement
if lyr.showLabels:
which means the layer should have the 'Label Features' turned ON in the mxd. If not, the code wil not work.
The code below does not check the Label Features turned ON condition. So this works:
import arcpy
mxd = arcpy.mapping.MapDocument(r"C:\test\test.mxd")
for lyr in arcpy.mapping.ListLayers(mxd):
if lyr.supports("LABELCLASSES"):
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
No comments:
Post a Comment