Arcpy基础入门-4、arcpy工具进阶

在使用arcmap工具箱里的工具的时候,如果已经加载相应的图层或者数据,就可以使用下拉列表的方式进行选择,也就是说工具会自动加载这些图层只需要选择即可。这一节就说下如何自动化的选择图层和数据。

1、 设置参数类型为相应的Featurelayer、RasterLayer等带Layer的参数

看一个实例代码:

import arcpy  

#获取图层

fc = arcpy.GetParameter(0)

arcpy.RepairGeometry_management(fc)

按照教程三创建arcpy工具,设置参数时候如下进行设置:

就可以实现图层的自动选择,如下图:

 

2、 通过代码自动获得图层或者数据

看一个实例代码:

import arcpy, os

#Read parameters from dialog

mxdPath = arcpy.GetParameterAsText(0)

dfName = arcpy.GetParameterAsText(1)

layerName = arcpy.GetParameterAsText(2)

layerFile = arcpy.GetParameterAsText(3)

outMXD = arcpy.GetParameterAsText(4)

#Update layer symbology

mxd = arcpy.mapping.MapDocument(mxdPath)

df = arcpy.mapping.ListDataFrames(mxd,dfName)[0]

updateLayer = arcpy.mapping.ListLayers(mxd,layerName)[0]

sourceLayer =arcpy.mapping.Layer(layerFile)

arcpy.mapping.UpdateLayer(df, updateLayer,sourceLayer, True)

 

#Save changes to new MXD and automaticallyopen

mxd.saveACopy(outMXD)

os.startfile(outMXD)

del mxd, sourceLayer

 其工具参数如下设置:

参数设置后面有个Validation

通过下面的Edit按钮可以对里面的代码进行编辑,编辑之后,点击保存,并点击下面的应用按钮即可。粘贴代码如下:

class ToolValidator:

 “””Class for validating a tool’s parameter values andcontrolling

  thebehavior of the tool’s dialog.”””

 

  def__init__(self):

   “””Setup the Geoprocessor and the list of toolparameters.”””

   import arcpy

   self.params = arcpy.GetParameterInfo()

 

  definitializeParameters(self):

   “””Refine the properties of a tool’s parameters.  This method is

   called when the tool is opened.”””

   return

 

  defupdateParameters(self):

   “””Modify the values and properties of parameters beforeinternal

   validation is performed.  Thismethod is called whenever a parmater

   has been changed.”””

   import arcpy

 

   #Update Data Frames list

   if self.params[0].value:

     mxd = arcpy.mapping.MapDocument(self.params[0].value.value)

 

     dataFrames = arcpy.mapping.ListDataFrames(mxd)

     dfList = []

     for df in dataFrames:

       dfList.append(df.name)

       dfList.sort()

     if not self.params[1].altered:

       self.params[1].filter.list = dfList

 

   #Update Layer list (in selected data frame)

   if self.params[1].value:

     df = arcpy.mapping.ListDataFrames(mxd, (self.params[1].value))[0]

     lyrs = arcpy.mapping.ListLayers(mxd, “”, df)

     layerList = []

     for lyr in lyrs:

       layerList.append(lyr.name)

       layerList.sort()

       

     if not self.params[2].altered:

       self.params[2].filter.list = layerList

   return

 

  defupdateMessages(self):

   “””Modify the messages created by internal validation foreach tool

   parameter.  This method is calledafter internal validation.”””

   return

转载自:https://blog.csdn.net/sprintwater/article/details/41146543

You may also like...