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
     def onClick(self):
         features = arcpy.UpdateCursor(r"D:\\SHP_test\\Point.shp")
         for feature in features:
             if feature.x == 99:
                feature.x = 4
         # Works fine
         del feature,features
  • Welcome to GIS SE! As a new user be sure to take the Tour to learn about our focussed Q&A format. What happens when you run your code? Please do not include unnecessary thanks - that is what upvotes on answers are for: meta.stackexchange.com/questions/2950 – PolyGeo Sep 29 '17 at 8:23
  • What happens when you run your code? Not what is meant to happen when you run your code. – PolyGeo Sep 29 '17 at 10:00
  • when i ran the code all the features with the 99 value change to 4 and i want to change just features that are selected in ArcGIS Desktop – Iheb Sep 29 '17 at 10:14
  • 1
    Please edit the question in response to requests for clarification. It's not fair to those who would answer to need to mine the comments for critical information. – Vince Sep 29 '17 at 10:53

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
  • I'm very thankful for your help it's exactly what i want – Iheb Oct 16 '17 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.