Accessing GH canvas componens from Python (outside of GH)

Hi @Jarek,

there a several ways. The easiest, wich i used since Rhino 5 is to get hold of the plugin object and access the GH_RhinoScriptInterface documented here. Using this you can make a full roundtrip and set values, but you cannot easily get values from components. An example using the plugin object can be found here.

Since Rhino 6, i switched to using the Grasshopper SDK more often. After importing the whole Grasshopper namespace you have full access to almost everything. To get and set slider values you could do something like this:

  • ping the open grasshopper document
  • check if the DisplayName matches your target document name
  • find the gh objects (components by name) using FindObjects
  • Optionally, compare the search results obj.InstanceGuid with an id
  • Optionally, compare the search results obj.NickName with a name
  • Once you have the slider component obj(s) you can get values from it
import Grasshopper as gh

# TODO: get doc and slider object

# validate this is a slider
if not isinstance(slider, gh.Kernel.Special.GH_NumberSlider):
    return

# get slider values and range
print "CurrentValue:", slider.Slider.Value
print "Minimum:", slider.Slider.Minimum
print "Maximum:", slider.Slider.Maximum

# set a slider value
slider.Slider.RaiseEvents = False
slider.ExpireSolution(True)
slider.SetSliderValue(new_value)  # caution !
slider.ExpireSolution(False)
slider.Slider.RaiseEvents = True

# update solution (recalculates all objects)
mydoc.NewSolution(True) 

When setting a new slider value, it has to be noted that you’re using the proper format and range. Integers are easy but with decimals some notes have to be taken. Eg. cultural differences when a system uses comma instead of point as decimal sign. I appreciate if @piac will jump in here if above code snippet would break something. He wrote a whole post about setting slider values without breaking something. So far, above did work for me but i am just toying around with GH still.

_
c.

1 Like