ArcPy – Troubleshooting Layer.setSelectionSet() Not Working in Python Add-In

arcmaparcpypython-addinselect

Using ArcGIS 10.8 (Desktop), I use a few lines of Python to set the selection in a layer called 'HNVKartierung' in a dataframe called 'HNVDaten' to a certain OID in order to then zoom to the selected extent. It works fine if I enter these lines (either one after the other or as a block) in the Python Window in ArcGIS:

import arcpy
mxd = arcpy.mapping.MapDocument('current')
df = arcpy.mapping.ListDataFrames(mxd, 'HNVDaten') [0]
lyr = arcpy.mapping.ListLayers(mxd, 'HNVKartierung', df)[0]
lyr.setSelectionSet('NEW',[1050])
df.zoomToSelectedFeatures()

However, if I include exactly the same lines # 2 to 5 (copy/paste) in the code of a Python script that's used for an add-in button, the selection of my feature layer isn't changed. The rest of the code in the add-in script works, however – that is, if there already is a selection on the feature layer, then the dataframe zooms to these features and if not, it zooms to the whole extent of the feature layer. The complete code for the add-in is:

class PAN(object):
 def __init__(self):
    self.enabled = True
    self.checked = False
def onClick(self):
    mxd = arcpy.mapping.MapDocument('current')
    df = arcpy.mapping.ListDataFrames(mxd, 'HNVDaten') [0]
    lyr = arcpy.mapping.ListLayers(mxd, 'HNVKartierung', df)[0]
    lyr.setSelectionSet('NEW',[1050])
    df.zoomToSelectedFeatures()
    pass

2021/9/27: It doesn't change anything if I use selection by attribute instead of setting the selection set:

arcpy.SelectLayerByAttribute_management("lyr", "NEW_SELECTION", ' "OBJECTID" = 1050 ')

Same result: works as a standalone script, isn't working within the add-in.

Best Answer

I tried a few more things and it seems clear to me that the problem is not selecting in the layer but addressing the layer at all - all other functions for layers I tried didn't work either if included in the add-in (e. g. changing visibility). Since I don't strictly need an add-in but can add the functionality as a tool script, I won't try any more. Thanks for your suggestions.