ArcGIS Desktop Python addIns

  • 格式:pdf
  • 大小:717.60 KB
  • 文档页数:34

An add-in is a customization, such as a collection of tools on a toolbar, that plugs into an ArcGIS for Desktop application (that is, ArcMap, ArcCatalog, ArcGlobe, and ArcScene) to provide supplemental functionality for accomplishing custom tasks.ArcGIS 10 introduced a new and innovative Desktop add-in model, making it easier for you to customize and extend the ArcGIS for Desktop applications. The new add-in model provides you with a declarative-based framework for creating a collection of customizations conveniently packaged within a single, compressed file with a .esriaddin file extension. In ArcGIS 10, add-ins are authored using .NET or Java along with Extensible Markup Language (XML). The XML describes the customizations, while the .NET or Java classes provide the custom behavior. The ArcObjects software development kit (SDK) includes an Add-Ins Wizard that integrates with development environments —such as Eclipse, Microsoft Visual Studio, and the free Express Editions of Visual Studio —to simplify development.ArcGIS 10.1 introduces Python to the list of languages for authoring Desktop add-ins, providing you with an easy solution to extend desktop functionality. To simplify the development of Python add-ins, you must download and use the Python Add-In Wizard to declare the type of customization. The wizard will generate all the required files necessary for the add-in to work. Click here to download the Python Add-In Wizard .A Python add-in is a single compressed file with a .esriaddin extension. It contains the following items:l config.xml —An Extensible Markup Language (XML) file defining the static add-in properties (for example, author, version, caption, category, and so on).l Python script —The Python script (.py file) containing your business logic.lResource files —Items, such as images, and in some cases, data that is used to support your add-in. As a single, compressed file, add-ins are easy to share between users and plugged into a desktop application by copying the add-in file to a well-known folder and removed by deleting it from this folder.For more information about sharing add-ins, see Sharing add-ins .Knowing when to create a Python add-inBefore you decide to make an add-in, be sure it is the right development path for your project requirements.If you want to add a collection of existing tools on a toolbar, or change the layout of menus or toolbars in an ArcGIS for Locate topicArcGIS 10.1What is a Python add-in?Desktop application, you can configure the user interface (UI) to match your preferences. This does not require any programming or scripting. For more information, see About configuring the user interface . For more information about adding geoprocessing tools on a toolbar or menu, see Adding and removing tools on menus and toolbars .If you need to run a set of geoprocessing tools to perform data analysis or data management, or produce a series of maps, consider creating a model with ModelBuilder or writing a Python script. For more information, see Geoprocessing with ModelBuilder , Geoprocessing with Python , and Automating map workflows .If it is required to make a customization that performs an action in response to an event, or requires the use of the mouse to interact with the display, you should consider making an add-in. An example is a tool that requires the user to click and drag a rectangle over a map to define an area of interest. Another example is an application extension that saves the map document automatically anytime a layer is added or removed from the table of contents.Getting started with Python add-insThe following topics guide you through workflows that are available for Python users to create specific types of desktop add-ins: Creating an add-in project Creating an add-in toolbar Creating an add-in menu Creating an add-in button Creating an add-in tool Creating an add-in combo box Creating an add-in tool palette Creating an add-in application extensionThe .esriaddin file is the key to sharing a Python add-in; all that other users need to do to execute the add-in is install the .esriaddin file on their machine or reference it using a network share.Desktop add-ins are loaded by ArcGIS for Desktop applications when the add-in file is discovered in one of several well-known add-in folders . Add-in files can be copied directly to one of these folders or to the appropriate folder automatically using ESRI ArcGIS Add-In Installation Utility .ArcGIS Add-In Installation UtilityESRI ArcGIS Add-In Installation Utility opens when an .esriaddin file is double-clicked. This utility is operational in Windows Explorer, through popular e-mail applications such as Outlook, and on web pages running on servers that have been configured to deploy add-in files (such as ArcGIS Online).When ESRI ArcGIS Add-In Installation Utility is invoked, it analyzes the metadata of the selected add-in file anddisplays the author's name, a description of the add-in, and whether the add-in contains a trusted digital signature. See the following illustration:Note:Not all areas of ArcGIS are exposed in Python. For more information about Pythoncapabilities and functionality, see A quick tour of ArcPy and Scripts for map document management and output .Copyright ©1995-2012 Esri. All rights reserved.Locate topic Sharing and installing add-insThis information can be used to decide whether to install the add-in. If the user elects to install the add-in, the utility copies the add-in to the user's default add-in folder.Add-ins are not backward compatible. Add-ins targeting 10.1, for example, will not work with 10.0 but will work with 10.2.The installation utility copies the add-in file to a generated subfolder under the well-known add-in folder; the subfolder is automatically generated based on the globally unique identifier (GUID) specified in the add-in file metadata. Thissubfolder prevents file naming conflicts that might otherwise occur if several add-ins have the same file name.Although add-ins can be manually copied to a default add-in folder, doing so bypasses the security and name conflict checks the add-in installation utility performs. For this reason, use the installation utility to install an add-in in ArcGIS for Desktop applications.Sharing add-ins on a networkAdd-ins can also be distributed within a private network using a trusted network share. Add-in files can be copied to these locations and automatically picked up by clients who've added the network share to their add-in folder list.Additional add-in folders are added using Add-In Manager , as illustrated below.In this scenario, multiple users can benefit from add-ins managed in a central location. If an add-in needs an update, the newer version can be copied over the existing version (even if in use). Clients automatically get the updated version of the add-in the next time they restart the corresponding desktop application.Determining add-in customizationsOnce an add-in has been installed, Add-In Manager —accessed from the Customize menu —makes it easy to determine the customizations it contains. The following illustration shows an add-in with a toolbar and a tool:Note:The default add-in folder for ArcGIS 10.1 on a Windows 7 or Windows Vistamachine is as follows:C:\Users\<username>\Documents\ArcGIS\AddIns\Desktop10.1The following add-in types can be created for ArcGIS Desktop applications using Python:Related Topics ...Project ...Button ...Tool bo BoxCopyright © 1995-2012 Esri. All rights reserved. Zoom In tool in ArcMap is a good example map before the display is redrawn, showing the map contents in greater detail for the specifiedarea. Tools may exist on toolbars and tool palettes.data with a known coordinate system is added to ArcMap, the scale combo box is enabled givingthe user a set of predefined scales from which to choose. It also allows a user to type a new scaleLocate topicTypes of Python Add-Ins...Toolbar ...Tool Palette ...Add-In Menu ...Application ExtensionTo simplify the development of add-ins, it is recommended that you use Python Add-In Wizard to declare the type of customization. Python Add-In Wizard reduces development time and possible errors by creating the files and folders necessary for the add-in to work. Download the Python Add-In Wizard .The download is a compressed ZIP file (.zip) containing all the files necessary to support the wizard. To use the wizard, unzip the contents to a folder and locate the executable file named addin_assistant.exe in the bin folder; double-click this executable to launch the wizard. Examples of using Python Add-In Wizard are provided in the topics for creating an add-in.This document introduces concepts that are essential for understanding how add-ins are created with Python.Python Add-In WizardTo simplify the development of add-ins, it is recommended that you use Python Add-In Wizard to declare the type of customization. Python Add-In Wizard reduces development time and possible errors by creating the files and folders necessary for the add-in to work. Download the Python Add-In Wizard .The download is a compressed ZIP file (.zip) containing all the files necessary to support the wizard. To use the wizard, unzip the contents to a folder and locate the executable file named addin_assistant.exe in the bin folder; double-click this executable to launch the wizard. Examples of using Python Add-In Wizard are provided in the topics for creating an add-in.File and folder structureAn add-in is a collection of files and folders conveniently packaged in a compressed file containing an .esriaddin extension to make them easily identifiable by users and ESRI ArcGIS Add-In Installation Utility . For example, if you double-click an add-in in Windows Explorer, on a website, or in an e-mail, the add-in installation utility automatically installs the add-in on your machine, deploying it to a well-known folder.Copyright © 1995-2012 Esri. All rights reserved. Tip:Create a shortcut of the executable file on your desktop or quick launch toolbar.Copyright © 1995-2012 Esri. All rights reserved.Tip:Create a shortcut of the executable file on your desktop or quick launch toolbar.Locate topicLocate topicEssential Python add-in concepts Obtaining the Python Add-In WizardAdd-ins have a config.xml file located at the root level of the add-in archive. This file describes the add-in and declares its customizations. It is created by Python Add-In Wizard when you click the Save button and includes all theinformation describing the add-in such as the ArcGIS product, captions, ToolTips, help information, images, and layout details.Add-ins also have an Install folder. The main purpose of the Install folder is to hold the Python script (the active portion) of the add-in. For example, a button is declared in the configuration file, but its custom behavior is defined in itsassociated Python script.You can create additional folders and files in the Install folder. This is useful in cases where you want to ship data as part of your add-in. This data can include items such as layer files, toolboxes, and .xml files. To access data located inside the installation location, you can take advantage of the __file__ built-in function. This example shows how to access a layer file in a data folder located within the installation folder:Most of the add-in types declared have graphics associated with them. All graphics entered through the wizard will be referenced in the configuration file and copied to the Images folder at the root level of the archive.The following graphic illustrates the file and folder structure of an add-in file (.esriaddin ):makeaddin.pyThe makeaddin.py Python file is a utility script created by Python Add-In Wizard and is used to package the files and folders within the project folder into the compressed add-in file. Double-click this file to create the add-in file. Each time you make changes to the add-in, you must run this script to repackage the add-in file with the latest updates.Well-known folder locationsAdd-ins are automatically discovered when ArcGIS for Desktop is started in a per user/per desktop version well-known folder. For example:lVista/7: C:\Users\<username>\Documents\ArcGIS\AddIns\Desktop10.1 l XP: C:\Documents and Settings\<username>\My Documents\ArcGIS\AddIns\Desktop10.1Add-ins are automatically added and removed using ESRI ArcGIS Add-In Installation Utility and the Add-In Manager dialog box. The Add-In Managerdialog box within ArcGIS for Desktop also allows you to add your own well-knowneq_layer = os.path.join(os.path.dirname(__file__), r'data\earth_quakes.lyr')folders, which can be network shares.In addition, add-ins automatically unpack their Install folder's contents to a temporary folder. For example:lVista/7: C:\Users\<username>\AppData\Local\ESRI\Desktop10.1\AssemblyCache l XP: C:\Documents and Settings\<username>\Local Settings\Application Data\ESRI\Desktop10.1\AssemblyCacheThis data is automatically removed by the add-in framework once it detects the add-in is no longer installed on the system.Creating an add-in projectThe first step to creating any add-in is the creation of an add-in project. This topic guides you through the step-by-step process of creating a new add-in project using the Python Add-In Wizard .You must make sure that you have the Python Add-In Wizard installed. If you have not downloaded it, click here to download. These instructions define an add-in project for ArcMap. There are no differences in creating an add-in project for any of the supported ArcGIS for Desktop software products.Creating a Python add-in project consists of two steps:Steps:1.Choose an add-in project folder.Locate the addin_assistant.exe file in the location where you installed the Python Add-In Wizard anddouble-click. The Browse For Folder dialog box will open where you are required to enter a folder to storeyour add-in project. You must choose an empty folder or make a new folder. Click OK .2.Enter the project settings.Once a working folder is selected, the first panel of the wizard is displayed. This is where you enter theproject settings. These settings are the project's metadata and stored in the config.xmlfile. They becomeCopyright ©1995-2012 Esri. All rights reserved.Locate topic Creating an add-in projectimportant at deployment time when the add-in is being used.The following is a description of each setting found on the Project Settings tab:The properties name, company, version, description, and image are all used after your add-in project is deployed (see Sharing add-ins for steps on this process). The following illustrates an example of how this metadata is used in the Add-In Manager after your project is deployed. The Add-In Manager is located in the desktop application under theCustomizemenu.Once the project settings are entered, click the Save button on the bottom of the wizard. Do not close the wizard. The following steps include creating your add-in customizations. Click the Add-In Contents tab and proceed to one of the following topics for information and steps to create an add-in: Creating an add-in button Creating an add-in tool Creating an add-in combo box Creating an add-in toolbar Creating an add-in tool palette Creating an add-in menu Creating an add-in application extensionCreating a Python add-in buttonA button is the simplest form of customization that can be used to execute some business logic when clicked.This topic guides you through the process of creating a button on a new toolbar using the Python Add-In Wizard . Before beginning this workflow, make sure that you have created an ArcMap add-in project and specified the project settings. For more information, see Creating an add-in project . While this workflow shows you how to create a button for ArcMap, you can use this process to add a button to any ArcGIS for Desktop application. This topic examines the process of creating a simple Zoom to Selected Features button. The Python class that is created by the wizard is then examined in greater detail to explore the properties and methods that provide functionality to your button.Creating an add-in button consists of the following steps:Steps:1.Create a toolbar or menuOnce you have entered the required project settings, click the Add-In Contents tab and begin declaring youradd-in customizations. A button may reside on a toolbar or a menu. In this example, a new toolbar iscreated as a container for the button. See Creating an add-in toolbar for steps on creating your own toolbar.2.Create the buttonOnce you have entered the toolbar properties, you can create a new button. Right-click the new toolbarnamed "Toolbar" and select New Button. Copyright © 1995-2012 Esri. All rights reserved.Locate topic Creating a Python add-in buttonA button has a number of properties for you to set. The following is a list of all of the properties with aninformation that will be used when a user invokes context-sensitive help. These are pop-up topics thatremain on-screen until a user clicks somewhere else.The next illustration shows the caption used as text to identify the button on the toolbar:The Python class that is executed when the button is clicked in a desktop application. The PythonThis will create all the necessary files and folders within your working folder.3.Editing the Python scriptAt this stage, you have finished adding values for the properties needed to define the add-in button. Thenext step in this workflow is to edit the Python script and update the Python class to include the functionalityfor zooming to selected features. If no features are selected, it zooms to the full extent of all layers. To addthe functionality to the custom button, perform the following steps:a.Edit the Python script in the Install folder located in the working folder you created through thewizard.A class will exist with the same name as the Class property you entered above. You should notrename this class as the class name is referenced in the config.xml file. For the explanation ofeach function and property of the class, see the Button class topic.b.Add the following script code into the onClick(self) function.This code provides the functionality to zoom to the selected features. c.Save the script. 4.Testing the buttonOnce you have created the button and added your script code, it is important to make the add-in file andtest the add-in before sharing it. For these steps, see Testing an add-in .5.Sharing the add-inAfter testing the button and confirming it works as expected, you are ready to deploy and share the add-in.For more information, see Sharing add-ins . Related TopicsButtonCreating an add-in toolA tool is very similar to a button . However, a tool requires user interaction with the desktop application's display first and, based on that interaction, executes some business logic. The Zoom In tool in ArcMap is a good example —it requires that you click or drag a rectangle over a map before the display is redrawn, showing the map contents in greater detail for the specified area.This topic guides you through the process of creating a tool on a new toolbar using the Python Add-In Wizard . Before beginning this workflow, make sure that you have created an ArcMap add-in project and specified the project settings. For more information, see Creating an add-in project . While this workflow shows you how to create a tool for ArcMap, you can use this process to add a tool to any ArcGIS for Desktopapplication. This topic examines the process of creating a simple Create Fishnet tool. The Python class created by the add-in wizard is then examined in greater detail to explore the properties and methods that provide functionality to your tool.Creating an add-in tool consists of the following steps:Steps:1.Create a toolbar.Click the Add-In Contents tab and begin declaring your add-in customizations. A tool can reside on a toolbar butnot on a menu. See Creating an add-in toolbar for steps on creating your own toolbar.2.Create the tool.Right-click the new toolbar and choose New Tool .# Implementation of OnClick method of Button's classdef onClick(self):# Get the current map document and the first data frame.mxd = arcpy.mapping.MapDocument('current')df = arcpy.mapping.ListDataFrames(mxd)[0]# Call the zoomToSelectedFeatures() method of the data frame cldf.zoomToSelectedFeatures()Copyright © 1995-2012 Esri. All rights reserved.Locate topicCreating a Python add-in toolA tool has a number of properties for you to set. The following is a list of all the properties with an explanationthat appears when a user invokes context-sensitive help. These are pop-up topics that remain on-screen untilThe next illustration shows the caption used as the text to identify the tool on the toolbar:The Python class representing your tool. The Python class is where you write your business logic forthe user clicks somewhere else.and folders are created within your working folder.3.Edit the Python script and update the Python class to include the functionality for creating a fishnet of polygons. An area of interest is defined by dragging the mouse to create a rectangle. The size of the fishnet is set to 10rows by 10 columns. To add the functionality to the custom tool, perform the following steps:a.Edit the Python script in the Install folder located in the working folder you created through thewizard.A class will exist with the same name as entered through the wizard. Do not rename this class asthe class name is referenced in config.xml. For the explanation of each function and property of theclass, see the Tool class topic.b.Update the functions as shown below.This code provides the functionality to create a fishnet of polygons with 10 rows and 10 columns. c.Save the script. 4.Testing the toolOnce the tool is created and the script code is added, it is important to make the add-in file and test the add-inbefore sharing it. For these steps, see Testing an add-in .5.Deploy and share the add-in.For steps on deploying and sharing the add-in, see Sharing add-ins . Related TopicsToolCreating an add-in combo boxA combo box contains an editable field and a drop-down list. The user can select a value from the drop-down list, which appears at the user's request. If you make the combo box editable, the combo box will include an editable field into which the user can type a value. The scale combo box in ArcMap is a good example of a combo box. When data with a known coordinate system is added to ArcMap, the scale combo box is enabled, giving you a set of predefined scales from which to choose. It also allows you to type a desired scale not present in the list of options, and the map is displayed based on the value added.This topic guides you through the process of creating a combo box on a new toolbar using the Python Add-In Wizard .def __init__(self):self.enabled = Trueself.cursor = 3self.shape = 'Rectangle'def onRectangle(self, rectangle_geometry):"""Occurs when the rectangle is drawn and the mouse button is releaseThe rectangle is a extent object."""extent = rectangle_geometry# Create a fishnet with 10 rows and 10 columns.if arcpy.Exists(r'in_memory\fishnet'):arcpy.Delete_management(r'in_memory\fishnet')fishnet = arcpy.CreateFishnet_management(r'in_memory\fishnet','%f %f' %(extent.XMin, extent.YMin),'%f %f' %(extent.XMin, extent.YMax),0, 0, 10, 10,'%f %f' %(extent.XMax, extent.YMax),'NO_LABEL'%f %f %f %f' %(extent.XMin, extent.YMin, extarcpy.RefreshActiveView()return fishnetCopyright © 1995-2012 Esri. All rights reserved.Locate topicCreating a Python Add-In Combo BoxBefore beginning this workflow, make sure that you have created an ArcMap Add-In project and specified the project settings. For more information, see Creating an Add-In Project. While this workflow shows you how to create a combo box for ArcMap, you can use this process to add a combo box to any ArcGIS for Desktop application. This topic examines the process of creating a combo box with the list of layers from the table of contents. Selecting a layer will create a fishnet covering the full extent of the layer. The Python class created by the Add-In wizard is then examined in greater detail to explore the properties and methods that provide functionality to your combo box.Creating an Add-In combo box consists of the following steps:Steps:1.Create a toolbar .Once you have entered the required project settings, click the Add-In Contents tab and begin declaring yourAdd-In customizations. A combo box may reside on a toolbar but cannot exist on a menu. See Creating anAdd-In Toolbar for steps on creating a toolbar.2.Create the combo box.Once you have entered the toolbar properties, you can create a new combo box. Right-click the new toolbarand select New Combo Box from the context menu.A combo box has a number of properties for you to set. These properties are stored in the config.xml fileThe Python class is where you write your business logic for the combo box. This class is importantbecause it is executed whenever the combo box is edited or the selection changes. Use theinformation that will be used when a user invokes context-sensitive help. These are pop-up topics thatremain on-screen until a user clicks somewhere else.This will create all the necessary files and folders within your working folder.3.Editing the Python script.At this stage, you have finished adding values for the properties needed to define the Add-In combo box.The next step in this workflow is to edit the Python script and update the Python class to include thefunctionality for creating a fishnet of polygons. The combo box will be populated with the list of layers fromthe active data frame. When a layer is selected from the combo box, a fishnet is created using the extent ofthe layer with a size set to 10 rows by 10 columns. To add the functionality to the combo box, perform thefollowing steps:a.Edit the Python script in the Install folder located in the working folder you created through thewizard.A class will exist with the same name as entered through the wizard. You should not rename thisclass, as the class name is referenced in the config.xml . The class consists of multiple functionsand properties described in Combo box Class topic.b.Update the functions as shown below.This code provides the functionality to create a fishnet of polygons with 10 rows and 10 columnsusing the extent of the layer selected from the combo box. c.Save the script.# Business logic to implement the ComboBoxdef __init__(self):self.editable = Trueself.enabled = Truedef onSelChange(self, selection):# When a new layer is selected, create a new fishnet using the elayer = arcpy.mapping.ListLayers(self.mxd, selection)[0]desc = arcpy.Describe(layer.dataSource)extent = desc.Extentfishnet = arcpy.CreateFishnet_management(r'in_memory\fishnet','%f %f' %(extent.XMin, extent.YMin),'%f %f' %(extent.XMin, extent.YMax),0, 0, 10, 10,'%f %f' %(extent.XMax, extent.YMax),'NO_LABELS','%f %f %f %f' %(extent.XMin, extent.YMin, extentarcpy.RefreshActiveView()def onFocus(self, focused):# When the combo box has focus, update the combo box with the list ofif focused:self.mxd = arcpy.mapping.MapDocument('current')layers = arcpy.mapping.ListLayers(self.mxd)self.items = []for layer in layers:self.items.append()。