GHPython OnClicked

Hi All,
I’m new GH.
I’m trying to create a component by python. And take value from OnClicked.
So I set value k = 1 and output by a. But it’s warning “1. Solution exception:global name ‘k’ is not defined”.
Any ideas ?

from ghpythonlib.componentbase import executingcomponent as component
import Grasshopper, GhPython
import System
import Rhino
import rhinoscriptsyntax as rs

class MyComponent(component):

def AppendAdditionalComponentMenuItems(self, menu):
    item = Grasshopper.Kernel.GH_Component.Menu_AppendGenericMenuItem(
        menu, "This is an Additonal Menu!!", self.OnClicked, self.Icon_24x24, None, True, False);
    item.ToolTipText = "Additonal Menu";
def OnClicked(self, obj, args):
    try:
        k = 1
    except Exception, ex:
        System.Windows.Forms.MessageBox.Show(str(ex))
def RunScript(self, x, y):
    a = k
    # return outputs if you have them; here I try it for you:
    return a

k seems to be a local variable from within the scope of the OnClicked method, and is thus not available in RunScript.

You can declare it as static variable above all the functions but within the class scope:

class Bar:
    a = 10  # static variable
   
    def foo(self):
        print Bar.a


b = Bar()
b.foo()

Or as as an instance variable by declaring it as self.a in a constructor:

class Bar:
    def __init__(self):  # constructor
        self.a = 10  # instance variable
        
    def foo(self):
        print self.a


b = Bar()
b.foo()

Or even by declaring the instance variable at a strategic location in local scope, which might be ideal in your case:

class Bar:
    def do(self):
        self.a = 10  # instance variable
    
    def foo(self):
        print self.a


b = Bar()
b.do()
b.foo()
1 Like

Thank you.