Showing posts with label Python Add-ins. Show all posts
Showing posts with label Python Add-ins. Show all posts

Friday, November 6, 2015

Extending Python 3.x (online resource)

Who doesn't love C++/C, I sure do....

Here is a great guide to developing all your c/c++ extension here (https://docs.python.org/3.4/extending/).

Happy Coding!

Wednesday, July 24, 2013

Python Add-Ins and Tkinter

ArcGIS for Desktop does not support any python GUIs out of the box, but let's say we want to have a form pop-up anyway. As shown below


One way to do this is to create a wx python instance at start up, which is create before the desktop python loop is created.  You would then reference the wx loop instead of the ArcGIS python loop.. but it's complicated...  You can also see tons of forum posts like this, that describe how the in process causes python to crash with GUIs: http://gis.stackexchange.com/questions/36848/crashing-arcgis-10-1-add-ins-using-multiprocessing

Let's assume though you want to use Tkinter because it's core, it comes with the python install.  Tkinter is the out of the box GUI that comes with python, and if you want to learn more about it, you can check it out here.  

Since ArcGIS for Desktop runs python add-ins 'in process'.  We cannot use multiprocessing or subprocessing to launch another instance python and display the code.  This is essentially the thing hindering python GUI development in the 10.x framework.  To get around this issue, code must be executed out of process.  Luckily for python people, we can create toolboxes and reference those toolboxes through the ImportToolbox().  Toolboxes allow you to run code 'out of process', which means multiprocessing!  Pretty sweet.

Let's take a look at the code to generate the form:
import Tkinter
from Tkinter import *
import multiprocessing
import sys, os
import arcpy
def show_form():

    root =Tk()
    root.title('Button')
    Label(text='I am a button').pack(pady=15)

    #button are labels that react to mouse and keyboard events.
    #in this case the button is packed to be at the bottom of the root or
    #toplevel widget.

    Button( text='Button') .pack(side=BOTTOM)
    root.mainloop()
    
if __name__ == "__main__":
    pythonExe = os.path.join(sys.exec_prefix, 'python.exe')
    multiprocessing.set_executable(pythonExe)
    multiprocessing.freeze_support = True
    jobs = []
    pool = multiprocessing.Pool(1)
    jobs.append(pool.apply_async(show_form,[]))
    pool.close()
    pool.join()
    del pool
    del jobs
    arcpy.SetParameterAsText(0, True)   


Now that we have the code to create the form, create a new python toolbox. Add this script and make sure you UNCHECK 'Run python script in process'

Next create your python add-in toolbar and add a button.  Copy the python script and toolbox from above into your 'install' folder.  Begin editing the python add-in script as follows:
import arcpy
import pythonaddins
import os
class btnShowForm(object):
    """Implementation for tkinterTester_addin.button (Button)"""
    def __init__(self):
        self.enabled = True
        self.checked = False
    def onClick(self):
        tbx = arcpy.ImportToolbox(os.path.join(os.path.dirname(__file__), "scripts.tbx"))
        tbx.showform() # name of script in toolbox is showform

Finally all you have to do is create the .esriaddin file. Just double click on the makeaddin.py and install the addin.

When you run the add-in from ArcMap, you should see a pop-up appear.  Pretty cool!  The one down side is that ArcPy needs to reload, so it can cause a slight delay in showing the form.


Enjoy

Also, if you want Python GUI support in ArcGIS for Desktop, please vote up this (http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU).

Thursday, March 28, 2013

Support GUI Design in ArcGIS for Desktop

Please support this idea of having GUI designer in python built in with python add-ins.

It can be found here: http://ideas.arcgis.com/ideaView?id=087E00000004SmHIAU

Thanks everyone.

Friday, January 18, 2013

10.1 SP 1 32 bit vs 64 bit


I ran across an interesting forum posting about the differences of 32 vs 64 bit python.

Check it out here: http://forums.arcgis.com/threads/70241-10.1-sp-1-and-32-64-bit-Python-versions

It's worth a good read to understand if you install the 64-bit background processor provided at SP 1 how it operates and works on your machine.

Remember if you do install the 64-bit version of python, you will have to install the 64-bit of all your extensions as well.

Enjoy

Tuesday, December 18, 2012

Using env.addOutputsToMap

The environmental variable addOutputsToMap prevents geoprocessing task results from being displayed in the TOC.  This environmental property by default is set to true, so every tool's result will display in the table of contents in ArcMap.

When developing python add-ins, you should utilize this tool to prevent sub-processes results from being added to the map.  A good example of this, is if your python add-in creates a table if it doesn't exist for logging purposes.  Your end user does not want to see this table, or know it exists, but if addOutputsToMap is set to true, the value will display in the table of contents.  Changing it to false would prevent the data from showing.

Example:
from arcpy import env
env.addOutputsToMap = false
#... perform GP task...
env.addOutputsToMap = true

Enjoy

Friday, October 26, 2012

Creating a Dynamic Fishnet Tool - Python Addin

At 10.1, you can create python add-ins.  These add-ins are very much like add-ins in .NET, but they do not support GUI development.  This means that you can either just call a function after interacting with a map, or you can open an existing tool.

On the resources.arcgis.com page, one example given is the use of fishnet, but the grid sizes are static at 10x10.  This is a basic example,  much like the 'Hello World' examples in most programming languages, but what if you want user inputs into the fishnet tool?  Can it be done?  The answer is yes, but you need more add-in components to do it.

To use the code posted, you must first install the python add-in component for ArcGIS 10.1.  You can find that here.

After that is installed, create a new project, and add a toolbar, a tool, and two combo boxes.
When naming the ID and Class Name, do not use the same name.  This will lead to problem if you have to communicate between controls.
I called my controls the following:

  • toolbar - ID: analysisTB
  • combobox 1: ID: cboRows1, Class Name: cboRows
  • combobox 2: ID cboColumns1, Class Name: cboColumns
  • tool: ID: fishnetTool101 Class Name fishnetTool
The code behind will create multiple classes and events.  Erase the events that are not needed, so the control is not listening to events that are not needed. 


First code the combo box controls.  Here we will set the control values and store the values to a global variable rows and columns:


rows = 0
columns = 0
class cboClassColumns(object):
    """Implementation for fishnet_addin.cboColumns (ComboBox)"""
    def __init__(self):
        self.items = [i for i in xrange(1, 100)]
        self.editable = True
        self.enabled = True
        self.dropdownWidth = 'WWW'
        self.width = 'WWW'
    def onSelChange(self, selection):
        global columns
        columns = int(selection)
    def onEditChange(self, text):
        global columns
        try:
            columns = int(text)
        except:
            columns = 0
            pythonaddins.MessageBox("Please enter a valid integer", "Value Error")

class cboClassRow(object):
    """Implementation for fishnet_addin.cboRows (ComboBox)"""
    def __init__(self):
        self.items = [i for i in xrange(1, 100)]
        self.editable = True
        self.enabled = True
        self.dropdownWidth = 'WWW'
        self.width = 'WWW'
    def onSelChange(self, selection):
        global rows
        rows = int(selection)
    def onEditChange(self, text):
        global rows
        try:
            rows = int(text)
        except:
            rows = 0
            pythonaddins.MessageBox("Please enter a valid integer", "Value Error")

OnSelChange event sets the row or column value, and since I made my control editable, I validate the user's entry on the onEditChange event.

Next is the fishnet function.  This code goes behind button control in this example:


class fishnetClass(object):
    """Implementation for fishnet_addin.fishnetClassID (Tool)"""
    def __init__(self):
        self.enabled = True
        self.shape = "Rectangle"
        self.cursor = 3
    def onRectangle(self, rectangle_geometry):
        """ creates a temp fishnet polygon """
        extent = rectangle_geometry
        fishnet = None
        global rows
        global columns
        fshFC = r"in_memory\fishnet"
        if arcpy.Exists(fshFC):
            arcpy.Delete_management(fshFC)
        try:
            fishnet = arcpy.CreateFishnet_management(fshFC,
                            '%f %f' %(extent.XMin, extent.YMin),
                            '%f %f' %(extent.XMin, extent.YMax),
                            0, 0, int(rows), int(columns),
                            '%f %f' %(extent.XMax, extent.YMax),'NO_LABELS',
                            '%f %f %f %f' %(extent.XMin, extent.YMin, extent.XMax, extent.YMax),
                            'POLYGON')
            arcpy.RefreshActiveView()
            del extent
        except:
            pythonaddins.MessageBox("Cannot Run the Fishnet Tool", "Error Message")
        return fishnet

Run the makefile.py, and install the add in. Now you can create a dynamic fishnet tool using python.

Thursday, October 25, 2012

Using pythonaddins Messagebox

New 10.1, there is a module created for python add-ins.  It's called the pythonaddins module, and you can create a messagebox.  The messagebox object allows you to display messages to an end user.

The arcpy help can be found here.

So the messagebox can be defined as such:

MessageBox(message, title, {mb_type})

To use you just pass in a message and title as text.  The mb_type is the type of messagebox type value.  It supports the following types:

mb_type value
0
OK Only
1
OK/Cancel
2
Abort/Retry/Cancel
3
Yes/No/Cancel
4
Yes/No
5
Retry/Cancel
6
Cancel/Try Again/Continue


Complete Example:
>>> import pythonaddins
>>> result = pythonaddins.MessageBox("Press Cancel", "TITLE", 1)
>>> print result
Cancel


Simple Right!