Community
Fusion API and Scripts
Got a new add-in to share? Need something specialized to be scripted? Ask questions or share what you’ve discovered with the community.
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Calling a method on button click

1 REPLY 1
Reply
Message 1 of 2
jmperez6
1012 Views, 1 Reply

Calling a method on button click

Hello, I really need help here. So I'm trying to make a simple GUI with 4 buttons on it and once those buttons are clicked, a different python script/method is called. So the button I'm testing right now is called "_reference" and when it is clicked, it should call the createReference() method, but when I click it, nothing happens. Does anyone know what to do here?

I've also tried saving the createReference() method as a separate script and that doesn't work either.

 

I've attached the code below.

 

 

 

import adsk.core, adsk.fusion, adsk.cam, traceback#, testmodule, 
import ctypes
import tkinter as tk
from tkinter import filedialog
#from . import test3 as test3
#from . import temp as temp3
handlers = []

def run(context):
    ui = None
    try:
        global contextt
        contextt = context
        app = adsk.core.Application.get()
        ui  = app.userInterface
        #createReference()

        # Get the CommandDefinitions Collection
        cmdDefs = ui.commandDefinitions
        
        # Create a button command definition
        UTEP=cmdDefs.addButtonDefinition('UTEPid','UTEP FUSION 360 GUI','Perform some action.','Icons')
        #UTEP2=cmdDefs.addButtonDefinition('UTEP2id','UTEP 2nd button','Perform a second action','Icons2')

        # Connect to the command created event.
        UTEPMultiProcessButtonPressCommandCreated = UTEPMultiProcessButtonPressEventHandler()
        UTEP.commandCreated.add(UTEPMultiProcessButtonPressCommandCreated)
        handlers.append(UTEPMultiProcessButtonPressCommandCreated)        
        
        SolidCreatePanel=ui.allToolbarPanels.itemById('SolidCreatePanel')
        #NewCompDropDown=SolidCreatePanel.controls.itemById('FusionCreateNewComponentCommand')
        SolidCreatePanel.controls.addCommand(UTEP, 'FusionCreateNewComponentCommand', True)
        
        #UTEPPanel=ui.commandDefinitions.itembyId('UTEPid')
        #UTEPPanel.controls.addCommand(UTEP2)

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))





# Event handler for the UTEPMultiProcessButton.
class UTEPMultiProcessButtonPressEventHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            app = adsk.core.Application.get()
            ui = app.userInterface
            cmd = args.command
               
            inputs = cmd.commandInputs
            global commandId
            commandId = 'ComponentGallery'
            # Create tab input 1
            tabCmdInput1 = inputs.addTabCommandInput(commandId + '_table_1', 'Components 1');
            tab1ChildInputs = tabCmdInput1.children;

           
            # Create selection input
            selectionInput = tab1ChildInputs.addSelectionInput(commandId + '_selection', 'Select', 'Basic select command input')
            selectionInput.setSelectionLimits(0)
            
            
            tab1ChildInputs.addBoolValueInput('_browse', 'Browse', False, '', True)
            # Create bool value input with button style
            tab1ChildInputs.addBoolValueInput('_load', 'Load', False, '', True)
            tab1ChildInputs.addBoolValueInput('_place', 'Place', False, '', True)
            # Create bool value input with button style
            tab1ChildInputs.addBoolValueInput('_reference', 'Create Reference', False, '', True)
                        
            
            
            # Connect to the execute event.
            onExecute = CommandExecuteHandler()
            cmd.execute.add(onExecute)
            onInputChanged = UTEPMultiProcessButtonPressedCommandInputChangedHandler()
            cmd.inputChanged.add(onInputChanged)
            handlers.append(onInputChanged)
            
        except:
            if ui:
                ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	
        





class CommandExecuteHandler(adsk.core.CommandEventHandler):
        def __init__(self):
            super().__init__()
        def notify(self, args):
            try:
                app = adsk.core.Application.get()
                ui = app.userInterface
                command = args.firingEvent.sender
                ui.messageBox(('command: {} executed successfully').format(command.parentCommandDefinition.id))
                
            except:
                if ui:
                    ui.messageBox(('command executed failed: {}').format(traceback.format_exc()))

# Event handler for the execute event.
class UTEPMultiProcessButtonPressedCommandInputChangedHandler(adsk.core.InputChangedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        #eventArgs = adsk.core.CommandEventArgs.cast(args)

        # Code to react to the event.
        app = adsk.core.Application.get()
        ui  = app.userInterface
        try:
            temp = args.firingEvent.sender
            #command = args.firingEvent.sender   
            cmdInput = args.input#inputs.itemById
            inputs = temp.commandInputs
           
           
            tableInput = inputs.itemById(commandId + '_table_1')
           
            if cmdInput.id == '_place':
                addRow(tableInput)
            if cmdInput.id == '_load':
                addRow(tableInput)
            if cmdInput.id == '_browse':
                browse()
            if cmdInput.id == '_reference':
                createReference()
                
                
            else:
                ui.messageBox('Not the correct button.')
        except:
            if ui:
                ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	
        
def stop(context):
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        
        # Deleting UTEPMultiProcess Button
        UTEPMultiProcesscmdDef = ui.commandDefinitions.itemById('UTEPid')
        if UTEPMultiProcesscmdDef:
            UTEPMultiProcesscmdDef.deleteMe()
            
        SolidCreatePanel=ui.allToolbarPanels.itemById('SolidCreatePanel')
        UTEPMultiProcesscntrl = SolidCreatePanel.controls.itemById('UTEPid')
        if UTEPMultiProcesscntrl:
            UTEPMultiProcesscntrl.deleteMe()
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	

def createReference():
    
    app = adsk.core.Application.get()
    ui  = app.userInterface
    product = app.activeProduct
    design = adsk.fusion.Design.cast(product)
    
        
    #get the root component of the active design
    rootComp = design.rootComponent
        
        
    # Create sketch
    sketches = rootComp.sketches
    sketch = sketches.add(rootComp.xZConstructionPlane)
    sketchCircles = sketch.sketchCurves.sketchCircles
    centerPoint = adsk.core.Point3D.create(0, 0, 0)
    sketchCircles.addByCenterRadius(centerPoint, 3.0)

    sketchLines = sketch.sketchCurves.sketchLines
    sketchLines.addTwoPointRectangle(adsk.core.Point3D.create(4, 4, 0), adsk.core.Point3D.create(-4, -4, 0))
  
    # Get the profile defined by the circle
    prof = sketch.profiles.item(1)
    
    # Create an extrusion input
    extrudes = rootComp.features.extrudeFeatures
    extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
   
    # Define that the extent is a distance extent of 5 cm
    distance = adsk.core.ValueInput.createByReal(1)
    # Set the distance extent to be symmetric
    extInput.setDistanceExtent(True, distance)
    # Set the extrude to be a solid one
    extInput.isSolid = True
    
    # Create the extrusion
    ext = extrudes.add(extInput)
    
    # Get the body created by the extrusion
    body = ext.bodies.item(0)
    
    axes = rootComp.constructionAxes
    axisInput = axes.createInput()
    # Add by line
    if design.designType == adsk.fusion.DesignTypes.DirectDesignType:
        axisInput.setByLine(adsk.core.InfiniteLine3D.create(adsk.core.Point3D.create(0), adsk.core.Vector3D.create(1, 0, 0)))
        axes.add(axisInput)
    
        # Prepare reference data
        circularFace = None
        for face in body.faces:
            geom = face.geometry
            if geom.surfaceType == adsk.core.SurfaceTypes.CylinderSurfaceType:
                    circularFace = face
                    break
        
            linearEdge = None
            for edge in body.edges:
                edgeGeom = edge.geometry
                if edgeGeom.curveType == adsk.core.Curve3DTypes.Line3DCurveType:
                    linearEdge = edge
                    break
            
            faceOne = linearEdge.faces.item(0)
            faceTwo = linearEdge.faces.item(1)
            vertexOne = faceOne.vertices.item(0)
            vertexTwo = faceOne.vertices.item(1)
        
            # Add by circularFace
            axisInput.setByCircularFace(circularFace)
            axes.add(axisInput)
        
            # Add by perpendicular at point
            axisInput.setByPerpendicularAtPoint(faceOne, vertexOne)
            axes.add(axisInput)
        
#   Addby o planes
            axisInput.setByTwoPlanes(faceOne, faceTwo)
            axes.add(axisInput)
            
#   Addby o points
            axisInput.setByTwoPoints(vertexOne, vertexTwo)
            axes.add(axisInput)
            
        # Add by edge
            axisInput.setByEdge(linearEdge)
            axes.add(axisInput)
            
        # Add by normal to face at point
            axisInput.setByNormalToFaceAtPoint(faceTwo, vertexOne)
            axis = axes.add(axisInput)
            
        # Get health state of the axis
            health = axis.healthState
            if health == adsk.fusion.FeatureHealthStates.WarningFeatureHealthState or health == adsk.fusion.FeatureHealthStates.ErrorFeatureHealthState:
                    ctypes.windll.user32.MessageBoxW(0, "OH NO!", "Your title", 1)
                


 

1 REPLY 1
Message 2 of 2
ekinsb
in reply to: jmperez6

Below is a version of your program that gets further than what you had before.  There were a few small errors that I fixed, and there's a modeling problem in the createReference function that I didn't take the time to debug.  However, there's a bigger problem.  The command framework is very controlling as far as what you can do and when.  The idea with a command is that you're collecting up a set of inputs and then at the final execute you create the single final result.  It doesn't currently support creating several individual results.  You can create geometry in the executePreview event to show the user what the final result will be, but whatever you create here will be entirely aborted and you need to re-create each time they change a command input, and then re-create when the command is executed.

 

I see that you were referencing some TkInter libraries.  With a TkInter modeless dialog you can potentially do what you want because it will be outside of the command machinery.  A feature of using a command is that all of the work you do will be collected into a single transaction so that it can be undone in a single step.  You'll lose that if you don't use a command.

 

import adsk.core, adsk.fusion, adsk.cam, traceback#, testmodule, 
import ctypes
import tkinter as tk
from tkinter import filedialog
#from . import test3 as test3
#from . import temp as temp3
handlers = []

def run(context):
    ui = None
    try:
        global contextt
        contextt = context
        app = adsk.core.Application.get()
        ui  = app.userInterface
        #createReference()

        # Get the CommandDefinitions Collection
        cmdDefs = ui.commandDefinitions
        
        # Create a button command definition
        UTEP=cmdDefs.addButtonDefinition('UTEPid','UTEP FUSION 360 GUI','Perform some action.','Icons')
        #UTEP2=cmdDefs.addButtonDefinition('UTEP2id','UTEP 2nd button','Perform a second action','Icons2')

        # Connect to the command created event.
        UTEPMultiProcessButtonPressCommandCreated = UTEPMultiProcessButtonPressEventHandler()
        UTEP.commandCreated.add(UTEPMultiProcessButtonPressCommandCreated)
        handlers.append(UTEPMultiProcessButtonPressCommandCreated)        
        
        SolidCreatePanel=ui.allToolbarPanels.itemById('SolidCreatePanel')
        #NewCompDropDown=SolidCreatePanel.controls.itemById('FusionCreateNewComponentCommand')
        SolidCreatePanel.controls.addCommand(UTEP, 'FusionCreateNewComponentCommand', True)
        
        #UTEPPanel=ui.commandDefinitions.itembyId('UTEPid')
        #UTEPPanel.controls.addCommand(UTEP2)
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


# Event handler for the UTEPMultiProcessButton.
class UTEPMultiProcessButtonPressEventHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        try:
            app = adsk.core.Application.get()
            ui = app.userInterface
            cmd = args.command
               
            inputs = cmd.commandInputs
            global commandId
            commandId = 'ComponentGallery'
            # Create tab input 1
            tabCmdInput1 = inputs.addTabCommandInput(commandId + '_table_1', 'Components 1');
            tab1ChildInputs = tabCmdInput1.children;

           
            # Create selection input
            selectionInput = tab1ChildInputs.addSelectionInput(commandId + '_selection', 'Select', 'Basic select command input')
            selectionInput.setSelectionLimits(0)
            
            tab1ChildInputs.addBoolValueInput('_browse', 'Browse', False, '', True)
            # Create bool value input with button style
            tab1ChildInputs.addBoolValueInput('_load', 'Load', False, '', True)
            tab1ChildInputs.addBoolValueInput('_place', 'Place', False, '', True)
            # Create bool value input with button style
            tab1ChildInputs.addBoolValueInput('_reference', 'Create Reference', False, '', True)
                        
            # Connect to the execute event.
            onExecute = CommandExecuteHandler()
            cmd.execute.add(onExecute)
            onInputChanged = UTEPMultiProcessButtonPressedCommandInputChangedHandler()
            cmd.inputChanged.add(onInputChanged)
            handlers.append(onInputChanged)
            
        except:
            if ui:
                ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	
        
class CommandExecuteHandler(adsk.core.CommandEventHandler):
        def __init__(self):
            super().__init__()
        def notify(self, args):
            try:
                app = adsk.core.Application.get()
                ui = app.userInterface
                command = args.firingEvent.sender
                ui.messageBox(('command: {} executed successfully').format(command.parentCommandDefinition.id))
                
            except:
                if ui:
                    ui.messageBox(('command executed failed: {}').format(traceback.format_exc()))

# Event handler for the execute event.
class UTEPMultiProcessButtonPressedCommandInputChangedHandler(adsk.core.InputChangedEventHandler):
    def __init__(self):
        super().__init__()
    def notify(self, args):
        eventArgs = adsk.core.InputChangedEventArgs.cast(args)

        # Code to react to the event.
        app = adsk.core.Application.get()
        ui  = app.userInterface
        try:
            cmdInput = eventArgs.input
            inputs = eventArgs.inputs
          
            tableInput = inputs.itemById(commandId + '_table_1')
           
            if cmdInput.id == '_place':
                addRow(tableInput)
            elif cmdInput.id == '_load':
                addRow(tableInput)
            elif cmdInput.id == '_browse':
                browse()
            elif cmdInput.id == '_reference':
                createReference()
            else:
                ui.messageBox('Not the correct button.')
        except:
            if ui:
                ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	

        
def stop(context):
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        
        # Deleting UTEPMultiProcess Button
        UTEPMultiProcesscmdDef = ui.commandDefinitions.itemById('UTEPid')
        if UTEPMultiProcesscmdDef:
            UTEPMultiProcesscmdDef.deleteMe()
            
        SolidCreatePanel=ui.allToolbarPanels.itemById('SolidCreatePanel')
        UTEPMultiProcesscntrl = SolidCreatePanel.controls.itemById('UTEPid')
        if UTEPMultiProcesscntrl:
            UTEPMultiProcesscntrl.deleteMe()
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	


def addRow(tableInput):
    app = adsk.core.Application.get()
    ui  = app.userInterface
    ui.messageBox('In addRow')    


def browse():
    app = adsk.core.Application.get()
    ui  = app.userInterface
    ui.messageBox('In browse')    


def createReference():
    try:
        app = adsk.core.Application.get()
        ui  = app.userInterface
        ui.messageBox('in createReference')
        product = app.activeProduct
        design = adsk.fusion.Design.cast(product)
        
        #get the root component of the active design
        rootComp = design.rootComponent
            
        # Create sketch
        sketches = rootComp.sketches
        sketch = sketches.add(rootComp.xZConstructionPlane)
        sketchCircles = sketch.sketchCurves.sketchCircles
        centerPoint = adsk.core.Point3D.create(0, 0, 0)
        sketchCircles.addByCenterRadius(centerPoint, 3.0)
    
        sketchLines = sketch.sketchCurves.sketchLines
        sketchLines.addTwoPointRectangle(adsk.core.Point3D.create(4, 4, 0), adsk.core.Point3D.create(-4, -4, 0))
      
        # Get the profile defined by the circle
        prof = sketch.profiles.item(1)
        
        # Create an extrusion input
        extrudes = rootComp.features.extrudeFeatures
        extInput = extrudes.createInput(prof, adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
       
        # Define that the extent is a distance extent of 5 cm
        distance = adsk.core.ValueInput.createByReal(1)
        # Set the distance extent to be symmetric
        extInput.setDistanceExtent(True, distance)
        # Set the extrude to be a solid one
        extInput.isSolid = True
        
        # Create the extrusion
        ext = extrudes.add(extInput)
        
        # Get the body created by the extrusion
        body = ext.bodies.item(0)
        
        axes = rootComp.constructionAxes
        axisInput = axes.createInput()
        # Add by line
        if design.designType == adsk.fusion.DesignTypes.DirectDesignType:
            axisInput.setByLine(adsk.core.InfiniteLine3D.create(adsk.core.Point3D.create(0), adsk.core.Vector3D.create(1, 0, 0)))
            axes.add(axisInput)
        
            # Prepare reference data
            circularFace = None
            for face in body.faces:
                geom = face.geometry
                if geom.surfaceType == adsk.core.SurfaceTypes.CylinderSurfaceType:
                        circularFace = face
                        break
            
                linearEdge = None
                for edge in body.edges:
                    edgeGeom = edge.geometry
                    if edgeGeom.curveType == adsk.core.Curve3DTypes.Line3DCurveType:
                        linearEdge = edge
                        break
                
                faceOne = linearEdge.faces.item(0)
                faceTwo = linearEdge.faces.item(1)
                vertexOne = faceOne.vertices.item(0)
                vertexTwo = faceOne.vertices.item(1)
            
                # Add by circularFace
                axisInput.setByCircularFace(circularFace)
                axes.add(axisInput)
            
                # Add by perpendicular at point
                axisInput.setByPerpendicularAtPoint(faceOne, vertexOne)
                axes.add(axisInput)
            
                #   Addby o planes
                axisInput.setByTwoPlanes(faceOne, faceTwo)
                axes.add(axisInput)
                
                #   Addby o points
                axisInput.setByTwoPoints(vertexOne, vertexTwo)
                axes.add(axisInput)
                
                # Add by edge
                axisInput.setByEdge(linearEdge)
                axes.add(axisInput)
                
                # Add by normal to face at point
                axisInput.setByNormalToFaceAtPoint(faceTwo, vertexOne)
                axis = axes.add(axisInput)
                
                # Get health state of the axis
                health = axis.healthState
                if health == adsk.fusion.FeatureHealthStates.WarningFeatureHealthState or health == adsk.fusion.FeatureHealthStates.ErrorFeatureHealthState:
                    ctypes.windll.user32.MessageBoxW(0, "OH NO!", "Your title", 1)
    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))	

Brian Ekins
Inventor and Fusion 360 API Expert
Mod the Machine blog

Can't find what you're looking for? Ask the community or share your knowledge.

Post to forums  

Autodesk DevCon in Munich May 28-29th


Autodesk Design & Make Report