Can I instantiate specific component on the canvas with a script [Python]

Ported Python Example from link aboce: SDK mode, Rhino 6
Set y input to list access.
Disclaimer: I think there are some challenges with these types of operations. I forget exactly, but you might want to double check if you need to expire anything.
Capture

# ported from C#
#source: http://james-ramsden.com/instantiate-grasshopper-component/
from ghpythonlib.componentbase import executingcomponent as component
import Grasshopper, GhPython
import System
import os
import System.Drawing as sd
import random

class MyComponent(component):
    def RunScript(self, MakeSlider,y):
        if MakeSlider:
            self.make_Slider()
        else:
            pass
            
    def make_Slider(self):
        try:
            randomVal = random.random()
            #instantiate  new slider
            slid = Grasshopper.Kernel.Special.GH_NumberSlider()
            slid.CreateAttributes() #sets up default values, and makes sure your slider doesn't crash rhino
    
            #customise slider (position, ranges etc)
            inputcount = self.Params.Input[1].SourceCount
            slid.Attributes.Pivot = sd.PointF(self.Attributes.DocObject.Attributes.Bounds.Left - slid.Attributes.Bounds.Width - 30, self.Params.Input[1].Attributes.Bounds.Y + inputcount * 30)
            slid.Slider.Maximum = 10
            slid.Slider.Minimum = 0
            slid.Slider.DecimalPlaces = 2
            slid.SetSliderValue((randomVal * 10));
    
            #add slider to canvas.
            ghdoc = self.OnPingDocument()
            ghdoc.AddObject(slid, False)
    
            #Connect the new slider to this component
            self.Params.Input[1].AddSource(slid)
            if inputcount > 5:
                System.Windows.Forms.MessageBox.Show(str("Okay, let's not get carried away"))
                
        except Exception, ex:
            self.AddRuntimeMessage(Grasshopper.Kernel.GH_RuntimeMessageLevel.Warning, str(ex))
            print ex

InstantiateCompsPY.gh (6.7 KB)

2 Likes