[GIS] Python get selected features in arcgis

arcpypython-addin

How can I edit selected Attribute only with python 2.7

I want to select points in arcgis and then when I click on the button created by my python script I want the value of the selected features change automatically.

when i run the code, all the features with the value 99 changes to 4 and I want to only change the value of the features that are selected in my current mxd in ArcGIS Desktop

this is my script

 import arcpy import pythonaddins

 class EditFild(object):
     """Implementation for Tools_addin.EditFild_1 (Button)"""
     def __init__(self):
         self.enabled = True
         self.checked = False
         print('int')
     def onClick(self):
         features = arcpy.UpdateCursor(r"D:\\SHP_test\\Point.shp")
         for feature in features:
             if feature.x == 99:
                feature.x = 4
                features.updateRow(feature)
         # Works fine
         print("done")
         del feature,features

Best Answer

I think the issue here is that your cursor is accessing the shapefile on disk, as opposed to the layer inside the MXD and therefore it does not carry any selection information.

You need to get the Layer object which can be accomplished a number of ways depending on how you want the tool to work. One method would be to use the GetSelectedTOCLayerOrDataFrame() function from the pythonaddins module - naturally it requires the user to select the right layer, though you can account for this with simple checks.

Try the following - the UpdateCursor() here is from the data access module and offers faster performance :

def onClick(self):
     lyr = pythonaddins.GetSelectedTOCLayerOrDataFrame()

     # Can add checks here to ensure the layer selected is appropriate

     with arcpy.da.UpdateCursor(lyr,'x') as features:
         for feature in features:
             if feature[0] == 99:
                feature[0] = 4
                features.updateRow(feature)
     print("done")