How add a button in the Fusion 360 "navigation toolbar"

How add a button in the Fusion 360 "navigation toolbar"

jean-jacques_juille
Explorer Explorer
1,955 Views
13 Replies
Message 1 of 14

How add a button in the Fusion 360 "navigation toolbar"

jean-jacques_juille
Explorer
Explorer

Hi,
I want to add a button in the Fusion 360 "navigation toolbar" that could simulate pressing the "Escape" key.
I thank you in advance.

0 Likes
Accepted solutions (1)
1,956 Views
13 Replies
Replies (13)
Message 2 of 14

j4n.vokurka
Advocate
Advocate

Hello,

you can add a button to the NavBar like so:

 //declare constants
 std::string NavBarBtnID = "NavBarBtn";
 std::string NavBarBtnName = "NavBarBtn";

 //add commmand def
 Ptr<CommandDefinition> NavBarBtnCmdDef;
 NavBarBtnCmdDef = ui->commandDefinitions()->itemById(NavBarBtnID);
 if (!NavBarBtnCmdDef)
     NavBarBtnCmdDef = ui->commandDefinitions()->addButtonDefinition(NavBarBtnID, NavBarBtnName, "Sample btn", "");

 // add btn to the toolbar
 Ptr<Toolbar> navToolbar = ui->toolbars()->itemById("NavToolBar");
 Ptr<ToolbarControls> navToolbarControls = navToolbar->controls();
 bool wasAdded = navToolbarControls->addCommand(NavBarBtnCmdDef, "", false);

 

Message 3 of 14

jean-jacques_juille
Explorer
Explorer

Hi,
I'm really sorry but I forgot to specify that I want this add-in in Python

0 Likes
Message 4 of 14

j4n.vokurka
Advocate
Advocate

For the most part (there are some language specific differences), it's just about transcribing the syntax since you still work with the same API. For that you can use AI if you are lazy like me, but here you go:

# Declare constants
navBarBtnID = "NavBarBtn"
navBarBtnName = "NavBarBtn"
# Add command definition
navBarBtnCmdDef = ui.commandDefinitions.itemById(navBarBtnID)
if not navBarBtnCmdDef:
    navBarBtnCmdDef = ui.commandDefinitions.addButtonDefinition(navBarBtnID, navBarBtnName, "Sample btn", "")

# Add button to the toolbar
navToolbar = ui.toolbars.itemById("navToolBar")
navToolbarControls = navToolbar.controls
wasAdded = navToolbarControls.addCommand(navBarBtnCmdDef, "", False)



Message 5 of 14

jean-jacques_juille
Explorer
Explorer

Hi,
I created a new add-in in Python that I named "EscapeBtn", I edited the "EscapeBtn.py" file, I pasted your Python code just below the try def run(context) but apparently nothing is happening, I don't see a button added to my navigation toolbar (bottom). Forgive me but I'm a beginner and wonder if I pasted the code in the right place. Can you continue to help me?
Thanks in advance.

0 Likes
Message 6 of 14

j4n.vokurka
Advocate
Advocate

Hello, 

 

paste in the code please so I can check it.

0 Likes
Message 7 of 14

jean-jacques_juille
Explorer
Explorer

Below is the code for my Escapebtn.py file, Thank you for your patient :

 

# Assuming you have not changed the general structure of the template no modification is needed in this file.
from . import commands
from .lib import fusion360utils as futil


def run(context😞
    try:
        # Declare constants
        navBarBtnID = "NavBarBtn"
        navBarBtnName = "NavBarBtn"
        # Add command definition
        navBarBtnCmdDef = ui.commandDefinitions.itemById(navBarBtnID)
        if not navBarBtnCmdDef:
            navBarBtnCmdDef = ui.commandDefinitions.addButtonDefinition(navBarBtnID, navBarBtnName, "Sample btn", "")

        # Add button to the toolbar
        navToolbar = ui.toolbars.itemById("navToolBar")
        navToolbarControls = navToolbar.controls
        wasAdded = navToolbarControls.addCommand(navBarBtnCmdDef, "", False)
       
        # This will run the start function in each of your commands as defined in commands/__init__.py
        commands.start()

    except:
        futil.handle_error('run')


def stop(context😞
    try:
        # Remove all of the event handlers your app has created
        futil.clear_handlers()

        # This will run the start function in each of your commands as defined in commands/__init__.py
        commands.stop()

    except:
        futil.handle_error('stop')

 

0 Likes
Message 8 of 14

j4n.vokurka
Advocate
Advocate
Accepted solution

I have written the whole add-in from start, here's the code:

import traceback
import adsk.fusion
import adsk.core

# Declare constants
_app: adsk.core.Application = None
_ui: adsk.core.UserInterface = None
_handlers = []
_navBarBtnID = "NavBarBtn"
_navBarBtnName = "NavBarBtn"
_toolbar = "NavToolbar"

def run(context):
    try:
        global _app, _ui, _handlers, _navBarBtnID, _navBarBtnName, _toolbar
        _app = adsk.core.Application.get()
        _ui = _app.userInterface   

        # Add command definition
        navBarBtnCmdDef = _ui.commandDefinitions.itemById(_navBarBtnID)
        if not navBarBtnCmdDef:
            navBarBtnCmdDef = _ui.commandDefinitions.addButtonDefinition(_navBarBtnID, _navBarBtnName, "Sample btn", "Resources")

        # Connect to the command created event.
        sampleCommandCreated = SampleCommandCreatedEventHandler()
        navBarBtnCmdDef.commandCreated.add(sampleCommandCreated)
        _handlers.append(sampleCommandCreated)

        
        # for toolbar in _ui.toolbars:
        #     _app.log(toolbar.id)

        # Add button to the toolbar
        navToolbar = _ui.toolbars.itemById(_toolbar)
        navToolbarControls = navToolbar.controls
        escapeBtn = navToolbarControls.addCommand(navBarBtnCmdDef, "", False)
    except:
        if _ui:
            _ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))

# Event handler for the commandCreated event.
class SampleCommandCreatedEventHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
        cmd = eventArgs.command

        global _app, _handlers

        _ui.messageBox("Implement your logic here.")          


def stop(context):
    try:
        global _app, _ui, _handlers, _navBarBtnID, _navBarBtnName, _toolbar
        _app = adsk.core.Application.get()
        _ui = _app.userInterface
        
        # Clean up the UI.  
        navToolbar = _ui.toolbars.itemById(_toolbar)
        navToolbarControls = navToolbar.controls

        cntrl = navToolbarControls.itemById(_navBarBtnID)
        if cntrl:
            cntrl.deleteMe()

        navBarBtnCmdDef = _ui.commandDefinitions.itemById(_navBarBtnID)
        if not navBarBtnCmdDef:
            navBarBtnCmdDef.deleteMe()

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

Don't forget to adjust the path to icon to your own on line 22.

Message 9 of 14

jean-jacques_juille
Explorer
Explorer

Hi
I just tried your code and it works great. I just had a problem with the icon path. I had to replace the relative path of the icons with the absolute path. I am really pleased with your help and thank you very much.

0 Likes
Message 10 of 14

juha2008
Explorer
Explorer

I spent quite a lot of time trying to get buttons and icons working—probably several hours in total.

 

I wanted to promote a custom button to the toolbar from my Add-In, but it wouldn't work without an icon. Finding the correct paths to the icon felt like higher science!

 

Here's the code that finally worked for me:

 

 

cmd_definitions = ui.commandDefinitions
button = cmd_definitions.itemById('updateTextCommand')
if not button:
        button = cmd_definitions.addButtonDefinition('updateTextCommand', 'ButtonText', 'ButtonDescription', './Resources/Command')

 

 

 

Initially, I tried putting the images in the same folder as my Python code within the Add-In folder, but that didn't work. Eventually, I created a subfolder called Resources and another subfolder inside that named Command. I placed the images there for testing, and the file names that worked were: 32x32-normal.svg or 32x32-normal.png.

 

Important note: Fusion 360 seems to load all resources when it starts up. I wasted a lot of time before realizing that I needed to restart Fusion for the changes to take effect. Once I did that, everything worked fine. I tried so many different things that it's possible other setups would have worked after a restart—but I don't have the energy to test them all again!

 

I'm still unsure if the file naming is exactly right, but it seems to work. If you're looking for more info, you might want to check this reference: Fusion 360 Icon Reference.

 

Just wanted to share my experience for anyone else struggling with the same issue. Hope this helps!

0 Likes
Message 11 of 14

nubrandao
Collaborator
Collaborator

i just created a button, but now how can i add a script to run when pushing the new botton?

0 Likes
Message 12 of 14

juha2008
Explorer
Explorer

Here is my full Add-In code for reference. Please note to create Add-In instead of Script.

I have a model with user parameter which I could increase and decrease by 5 mm. Then if I change HeightQ paramter manually, then I have button to refresh certain sketch with text to have the dimension in it. For example parameter value is 15 mm, then sketch will have text in it "15 mm".

import os
import adsk.core, adsk.fusion

app = adsk.core.Application.get()
ui = app.userInterface
handlers = []

# Funktiot, joilla kasvatetaan ja pienennetään parametriarvoa ja päivitetään teksti
def change_height_param(increment):
    try:
        design = app.activeProduct
        if not design:
            ui.messageBox('Ei aktiivista suunnittelua')
            return

        userParams = design.userParameters
        heightParam = userParams.itemByName('HeightQ')

        if heightParam:
            new_value = heightParam.value + (increment / 10)  # Muutos senttimetreissä
            heightParam.value = new_value
            update_text_with_height_param()  # Päivitetään luonnoksen teksti
        else:
            ui.messageBox('Parametri HeightQ ei löytynyt')
    except Exception as e:
        ui.messageBox(f'Virhe parametrin muuttamisessa: {str(e)}')

# Tekstin päivitystoiminto (sama kuin ennen)
def update_text_with_height_param():
    try:
        design = app.activeProduct
        if not design:
            ui.messageBox('Ei aktiivista suunnittelua')
            return

        rootComp = design.rootComponent
        if not rootComp:
            ui.messageBox('Ei komponenttia saatavilla')
            return

        sketches = rootComp.sketches
        for sketch in sketches:
            if sketch.name == 'HeightText':
                userParams = design.userParameters
                heightParam = userParams.itemByName('HeightQ')

                if heightParam:
                    heightValue = int(heightParam.value * 10)  # Muunna senttimetreistä millimetreiksi
                    sketchTexts = sketch.sketchTexts
                    if sketchTexts.count > 0:
                        textElement = sketchTexts.item(0)
                        textElement.text = str(heightValue) + ' mm'
                    else:
                        ui.messageBox('Ei tekstielementtejä luonnoksessa')
                else:
                    ui.messageBox('Parametri HeightQ ei löytynyt')
    except Exception as e:
        ui.messageBox(f'Virhe tekstin päivityksessä: {str(e)}')

# Käsittelijät eri komennoille ilman ID-viittauksia
class IncreaseCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
            command = eventArgs.command
            onExecute = IncreaseCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)
        except Exception as e:
            ui.messageBox(f'Virhe Increase-komennon luonnissa: {str(e)}')

class IncreaseCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            change_height_param(5)  # Kasvatetaan 5 mm
        except Exception as e:
            ui.messageBox(f'Virhe Increase-komennossa: {str(e)}')

class DecreaseCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
            command = eventArgs.command
            onExecute = DecreaseCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)
        except Exception as e:
            ui.messageBox(f'Virhe Decrease-komennon luonnissa: {str(e)}')

class DecreaseCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            change_height_param(-5)  # Pienennetään 5 mm
        except Exception as e:
            ui.messageBox(f'Virhe Decrease-komennossa: {str(e)}')

class RefreshCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
            command = eventArgs.command
            onExecute = RefreshCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)
        except Exception as e:
            ui.messageBox(f'Virhe Refresh-komennon luonnissa: {str(e)}')

class RefreshCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            update_text_with_height_param()  # Päivitä tekstielementti luonnoksessa
        except Exception as e:
            ui.messageBox(f'Virhe Refresh-komennossa: {str(e)}')

# Komennon luonti
def create_adjustment_buttons():
    try:
        # Selvitä Add-Inin hakemisto ja muodosta oikea polku kuvakkeille
        addin_path = os.path.dirname(os.path.realpath(__file__))
        resources_path = os.path.join(addin_path, 'Resources')

        # Lisää Increase-nappula
        increase_button = ui.commandDefinitions.itemById('increaseHeightCommand')
        if not increase_button:
            increase_button = ui.commandDefinitions.addButtonDefinition(
                'increaseHeightCommand', 'Increase Height', 'Kasvattaa Height-parametrin arvoa 5 mm',
                os.path.join(resources_path, 'Plus')
            )

        # Lisää Decrease-nappula
        decrease_button = ui.commandDefinitions.itemById('decreaseHeightCommand')
        if not decrease_button:
            decrease_button = ui.commandDefinitions.addButtonDefinition(
                'decreaseHeightCommand', 'Decrease Height', 'Pienentää Height-parametrin arvoa 5 mm',
                os.path.join(resources_path, 'Minus')
            )

        # Lisää Refresh-nappula
        refresh_button = ui.commandDefinitions.itemById('refreshHeightCommand')
        if not refresh_button:
            refresh_button = ui.commandDefinitions.addButtonDefinition(
                'refreshHeightCommand', 'Refresh', 'Päivitä tekstielementti parametrin perusteella',
                os.path.join(resources_path, 'Refresh')
            )

        # Rekisteröi Increase-komento
        onIncreaseCreated = IncreaseCommandCreatedHandler()
        increase_button.commandCreated.add(onIncreaseCreated)
        handlers.append(onIncreaseCreated)

        # Rekisteröi Decrease-komento
        onDecreaseCreated = DecreaseCommandCreatedHandler()
        decrease_button.commandCreated.add(onDecreaseCreated)
        handlers.append(onDecreaseCreated)

        # Rekisteröi Refresh-komento
        onRefreshCreated = RefreshCommandCreatedHandler()
        refresh_button.commandCreated.add(onRefreshCreated)
        handlers.append(onRefreshCreated)

        # Lisää nappulat Modify-paneeliin ja promoted-tilaan
        workspace = ui.workspaces.itemById('FusionSolidEnvironment')
        toolbar_tab = workspace.toolbarTabs.itemById('SolidTab')
        modify_panel = toolbar_tab.toolbarPanels.itemById('SolidModifyPanel')

        if modify_panel:
            increase_control = modify_panel.controls.itemById('increaseHeightCommand')
            if not increase_control:
                increase_control = modify_panel.controls.addCommand(increase_button)
            increase_control.isPromoted = True

            decrease_control = modify_panel.controls.itemById('decreaseHeightCommand')
            if not decrease_control:
                decrease_control = modify_panel.controls.addCommand(decrease_button)
            decrease_control.isPromoted = True

            refresh_control = modify_panel.controls.itemById('refreshHeightCommand')
            if not refresh_control:
                refresh_control = modify_panel.controls.addCommand(refresh_button)
            refresh_control.isPromoted = True

    except Exception as e:
        ui.messageBox(f'Virhe komennon luomisessa: {str(e)}')

# Komennon käynnistys
def run(context):
    try:
        create_adjustment_buttons()  # Luo Increase, Decrease ja Refresh -nappulat käyttöliittymään
    except Exception as e:
        ui.messageBox(f'Virhe run-funktiossa: {str(e)}')

# Komennon lopetus
def stop(context):
    try:
        # Poista kaikki komennot ja tapahtumakäsittelijät
        cmd_definitions = ui.commandDefinitions

        # Poista Increase-nappula
        increase_button = cmd_definitions.itemById('increaseHeightCommand')
        if increase_button:
            increase_button.deleteMe()

        # Poista Decrease-nappula
        decrease_button = cmd_definitions.itemById('decreaseHeightCommand')
        if decrease_button:
            decrease_button.deleteMe()

        # Poista Refresh-nappula
        refresh_button = cmd_definitions.itemById('refreshHeightCommand')
        if refresh_button:
            refresh_button.deleteMe()

        workspace = ui.workspaces.itemById('FusionSolidEnvironment')
        toolbar_tab = workspace.toolbarTabs.itemById('SolidTab')
        modify_panel = toolbar_tab.toolbarPanels.itemById('SolidModifyPanel')

        if modify_panel:
            increase_control = modify_panel.controls.itemById('increaseHeightCommand')
            if increase_control:
                increase_control.deleteMe()

            decrease_control = modify_panel.controls.itemById('decreaseHeightCommand')
            if decrease_control:
                decrease_control.deleteMe()

            refresh_control = modify_panel.controls.itemById('refreshHeightCommand')
            if refresh_control:
                refresh_control.deleteMe()

        global handlers
        handlers = []
    except Exception as e:
        ui.messageBox(f'Virhe stop-funktiossa: {str(e)}')

I made this partly by help of ChatGPT.

 

Screenshot what kind of parameter model I have to update height and text on top surface of it.

juha2008_0-1729620233489.png

 

To get it all english, here is same code translated by ChatGPT (I cannot validate whether this is working or not, upper one is working for sure).

import os
import adsk.core, adsk.fusion

app = adsk.core.Application.get()
ui = app.userInterface
handlers = []

# Functions to increase and decrease the parameter value and update the text
def change_height_param(increment):
    try:
        design = app.activeProduct
        if not design:
            ui.messageBox('No active design')
            return

        userParams = design.userParameters
        heightParam = userParams.itemByName('HeightQ')

        if heightParam:
            new_value = heightParam.value + (increment / 10)  # Change in centimeters
            heightParam.value = new_value
            update_text_with_height_param()  # Update the sketch text
        else:
            ui.messageBox('Parameter HeightQ not found')
    except Exception as e:
        ui.messageBox(f'Error changing parameter: {str(e)}')

# Text update function (same as before)
def update_text_with_height_param():
    try:
        design = app.activeProduct
        if not design:
            ui.messageBox('No active design')
            return

        rootComp = design.rootComponent
        if not rootComp:
            ui.messageBox('No component available')
            return

        sketches = rootComp.sketches
        for sketch in sketches:
            if sketch.name == 'HeightText':
                userParams = design.userParameters
                heightParam = userParams.itemByName('HeightQ')

                if heightParam:
                    heightValue = int(heightParam.value * 10)  # Convert from centimeters to millimeters
                    sketchTexts = sketch.sketchTexts
                    if sketchTexts.count > 0:
                        textElement = sketchTexts.item(0)
                        textElement.text = str(heightValue) + ' mm'
                    else:
                        ui.messageBox('No text elements in the sketch')
                else:
                    ui.messageBox('Parameter HeightQ not found')
    except Exception as e:
        ui.messageBox(f'Error updating text: {str(e)}')

# Handlers for different commands without ID references
class IncreaseCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
            command = eventArgs.command
            onExecute = IncreaseCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)
        except Exception as e:
            ui.messageBox(f'Error creating Increase command: {str(e)}')

class IncreaseCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            change_height_param(5)  # Increase by 5 mm
        except Exception as e:
            ui.messageBox(f'Error executing Increase command: {str(e)}')

class DecreaseCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
            command = eventArgs.command
            onExecute = DecreaseCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)
        except Exception as e:
            ui.messageBox(f'Error creating Decrease command: {str(e)}')

class DecreaseCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            change_height_param(-5)  # Decrease by 5 mm
        except Exception as e:
            ui.messageBox(f'Error executing Decrease command: {str(e)}')

class RefreshCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            eventArgs = adsk.core.CommandCreatedEventArgs.cast(args)
            command = eventArgs.command
            onExecute = RefreshCommandExecuteHandler()
            command.execute.add(onExecute)
            handlers.append(onExecute)
        except Exception as e:
            ui.messageBox(f'Error creating Refresh command: {str(e)}')

class RefreshCommandExecuteHandler(adsk.core.CommandEventHandler):
    def __init__(self):
        super().__init__()

    def notify(self, args):
        try:
            update_text_with_height_param()  # Update the text element in the sketch
        except Exception as e:
            ui.messageBox(f'Error executing Refresh command: {str(e)}')

# Command creation
def create_adjustment_buttons():
    try:
        # Determine Add-In directory and form the correct path for icons
        addin_path = os.path.dirname(os.path.realpath(__file__))
        resources_path = os.path.join(addin_path, 'Resources')

        # Add Increase button
        increase_button = ui.commandDefinitions.itemById('increaseHeightCommand')
        if not increase_button:
            increase_button = ui.commandDefinitions.addButtonDefinition(
                'increaseHeightCommand', 'Increase Height', 'Increase Height parameter by 5 mm',
                os.path.join(resources_path, 'Plus')
            )

        # Add Decrease button
        decrease_button = ui.commandDefinitions.itemById('decreaseHeightCommand')
        if not decrease_button:
            decrease_button = ui.commandDefinitions.addButtonDefinition(
                'decreaseHeightCommand', 'Decrease Height', 'Decrease Height parameter by 5 mm',
                os.path.join(resources_path, 'Minus')
            )

        # Add Refresh button
        refresh_button = ui.commandDefinitions.itemById('refreshHeightCommand')
        if not refresh_button:
            refresh_button = ui.commandDefinitions.addButtonDefinition(
                'refreshHeightCommand', 'Refresh', 'Update text element based on parameter',
                os.path.join(resources_path, 'Refresh')
            )

        # Register Increase command
        onIncreaseCreated = IncreaseCommandCreatedHandler()
        increase_button.commandCreated.add(onIncreaseCreated)
        handlers.append(onIncreaseCreated)

        # Register Decrease command
        onDecreaseCreated = DecreaseCommandCreatedHandler()
        decrease_button.commandCreated.add(onDecreaseCreated)
        handlers.append(onDecreaseCreated)

        # Register Refresh command
        onRefreshCreated = RefreshCommandCreatedHandler()
        refresh_button.commandCreated.add(onRefreshCreated)
        handlers.append(onRefreshCreated)

        # Add buttons to the Modify panel and promote them
        workspace = ui.workspaces.itemById('FusionSolidEnvironment')
        toolbar_tab = workspace.toolbarTabs.itemById('SolidTab')
        modify_panel = toolbar_tab.toolbarPanels.itemById('SolidModifyPanel')

        if modify_panel:
            increase_control = modify_panel.controls.itemById('increaseHeightCommand')
            if not increase_control:
                increase_control = modify_panel.controls.addCommand(increase_button)
            increase_control.isPromoted = True

            decrease_control = modify_panel.controls.itemById('decreaseHeightCommand')
            if not decrease_control:
                decrease_control = modify_panel.controls.addCommand(decrease_button)
            decrease_control.isPromoted = True

            refresh_control = modify_panel.controls.itemById('refreshHeightCommand')
            if not refresh_control:
                refresh_control = modify_panel.controls.addCommand(refresh_button)
            refresh_control.isPromoted = True

    except Exception as e:
        ui.messageBox(f'Error creating command: {str(e)}')

# Command start
def run(context):
    try:
        create_adjustment_buttons()  # Create Increase, Decrease, and Refresh buttons in the UI
    except Exception as e:
        ui.messageBox(f'Error in run function: {str(e)}')

# Command stop
def stop(context):
    try:
        # Remove all commands and event handlers
        cmd_definitions = ui.commandDefinitions

        # Remove Increase button
        increase_button = cmd_definitions.itemById('increaseHeightCommand')
        if increase_button:
            increase_button.deleteMe()

        # Remove Decrease button
        decrease_button = cmd_definitions.itemById('decreaseHeightCommand')
        if decrease_button:
            decrease_button.deleteMe()

        # Remove Refresh button
        refresh_button = cmd_definitions.itemById('refreshHeightCommand')
        if refresh_button:
            refresh_button.deleteMe()

        workspace = ui.workspaces.itemById('FusionSolidEnvironment')
        toolbar_tab = workspace.toolbarTabs.itemById('SolidTab')
        modify_panel = toolbar_tab.toolbarPanels.itemById('SolidModifyPanel')

        if modify_panel:
            increase_control = modify_panel.controls.itemById('increaseHeightCommand')
            if increase_control:
                increase_control.deleteMe()

            decrease_control = modify_panel.controls.itemById('decreaseHeightCommand')
            if decrease_control:
                decrease_control.deleteMe()

            refresh_control = modify_panel.controls.itemById('refreshHeightCommand')
            if refresh_control:
                refresh_control.deleteMe()

        global handlers
        handlers = []
    except Exception as e:
        ui.messageBox(f'Error in stop function: {str(e)}')

 

0 Likes
Message 13 of 14

juha2008
Explorer
Explorer

Buttons on the Toolbar:

juha2008_0-1729621011177.png

 

Resources folder structure and files (Command folder were just testing):

juha2008_1-1729621137676.png

Also 16x16-normal.png files is also extra and they are not... Well.. After quick double check. They are used in dropdown toolbar apparently. So those I need to update for better look:

juha2008_2-1729621287858.png

 

0 Likes
Message 14 of 14

nubrandao
Collaborator
Collaborator

for example, i used chatgpt to create a button, 

import adsk.core, adsk.fusion, traceback

app = adsk.core.Application.get()
ui  = app.userInterface

def run(context😞
    try:
        # Activate the CAM (Manufacture) workspace
        workspaces = ui.workspaces
        manufacture_workspace = workspaces.itemById('CAMEnvironment')
        manufacture_workspace.activate()

        # Create a command definition for the button
        cmd_def = ui.commandDefinitions.addButtonDefinition('MyCAMToolButton',
                                                            'Run CAM Tool',
                                                            'This button runs my custom CAM tool.')

        # Define the custom action that will run when the button is clicked
        on_command_created = MyCommandCreatedHandler()
        cmd_def.commandCreated.add(on_command_created)
        handlers.append(on_command_created)

        # Add the button to the CAMJobPanel
        cam_job_panel = ui.allToolbarPanels.itemById('CAMJobPanel')
        if cam_job_panel:
            cam_job_panel.controls.addCommand(cmd_def)
            ui.messageBox('Button added to CAMJobPanel!')

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

def stop(context😞
    try:
        # Clean up the UI elements when the add-in is stopped
        cmd_def = ui.commandDefinitions.itemById('MyCAMToolButton')
        if cmd_def:
            cmd_def.deleteMe()

        # Remove the button from the CAMJobPanel
        cam_job_panel = ui.allToolbarPanels.itemById('CAMJobPanel')
        if cam_job_panel:
            cntrl = cam_job_panel.controls.itemById('MyCAMToolButton')
            if cntrl:
                cntrl.deleteMe()

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

class MyCommandCreatedHandler(adsk.core.CommandCreatedEventHandler😞
    def __init__(self😞
        super().__init__()

    def notify(self, args😞
        try:
            # Run your custom script or function here
            ui.messageBox('Custom CAM script is running!')
           
            # You can include your actual CAM tool script or logic here
            # For example, accessing toolpath data, generating G-code, etc.

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

# Event handlers array to prevent garbage collection
handlers = []
 
but everytime i try to add the script, dont work, how can i add a script inside the button?
0 Likes