I am unable to turn on the labels within my Python script:
import arcpy
mxd = arcpy.mapping.MapDocument(r"Mypathhere") #Map document reference
layer = arcpy.mapping.ListLayers(mxd, "Layername")[0] #Indexing list for 1st layer
if layer.supports("LABELCLASSES"):
for lblclass in layer.labelClasses:
lblclass.showClassLabels = True
arcpy.RefreshActiveView()
mxd.save()
del mxd
If I need to enable labeling in the label manager first, can that be done with ArcPy?
The script does not break. I do not get any errors. The points just do not get labeled.
3 Answers 3
I think your problem is that your code is enabling the checkbox under the Layer Properties that says "Label features in this class". The part you are missing is the code to enable to the checkbox for "Label features in this layer"
Try inserting this code:
layer.showLabels = True
After your if statement that activates the label classes, like the following:
import arcpy
mxd = arcpy.mapping.MapDocument(r"Mypathhere") #Map document reference
layer = arcpy.mapping.ListLayers(mxd, "Layername")[0] #Indexing list for 1st layer
if layer.supports("LABELCLASSES"):
for lblclass in layer.labelClasses:
lblclass.showClassLabels = True
layer.showLabels = True`
arcpy.RefreshActiveView()
mxd.save()
del mxd
If you are not always using label classes, and simply want to turn labels on, then the code can be simplified to:
import arcpy
mxd = arcpy.mapping.MapDocument(r"MyPathHere")
layer = arcpy.mapping.ListLayers(mxd, "LayerName")[0]
layer.showLabels = True
and if you want to do things like refresh the data/layout view (whichever is active), see the checkbox marked in the Table of Contents, and/or to save the changes to your map, then just add lines like:
arcpy.RefreshActiveView()
arcpy.RefreshTOC()
mxd.save()
I am working in arcpy for ArcGIS Pro, in a similar situation, and I wanted to say that
Try inserting this code:
layer.showLabels = True
from Get Spatial, above, worked for enabling my layer to support labeling. Here's what I am using as a test
lyr.showLabels = True
if lyr.supports("SHOWLABELS"):
if lyr.showLabels:
print("Layer name: " + lyr.name)
for lblClass in lyr.listLabelClasses():
print("\t Class Name: \t" + lblClass.name)
print("\t Expression: \t" + lblClass.expression)
print("\t SQL Query: \t" + lblClass.SQLQuery)
else:
print("not show labels")
else:
print("not support show")