Search code examples
pythonstringmayafunction

How do I use Def Function strings in maya


I've been transposing from mel and was wondering if anyone could point me in the right direction with this. I'm not too sure how to run a Function with a specific arg in mind.

def testFUNCTION(field):
    if field == 'option1': print 'You have selected option 1'
    else: print 'You have selected option 2'

mc.window( w=150 )
mc.textFieldButtonGrp (l='option 1', bl='Set', ad3=2, bc=('testFUNCTION, option1'))
mc.textFieldButtonGrp (l='option 2', bl='Set', ad3=2, bc=('testFUNCTION, option2'))
mc.showWindow()

I keep getting:

line 1: name 'option1' is not defined

Any advise would be great! Thanks


Solution

  • You are trying to create the callback from a string when you pass

    mc.textFieldButtonGrp (l='option 1', bl='Set', ad3=2, bc=('testFUNCTION, option1')
    

    When the string is evaluated by Maya, 'option1' is not quoted so Python thinks its a variable name.

    In general you don't want to use the string format for callbacks for precisely this reason: there will be problems figuring out where variables are defined.

    The usual workarounds are to use the functools module or a lambda to create callbacks which have all the information they need when they are created. For example:

    def testFUNCTION(field):
        if field == 'option1': print 'You have selected option 1'
        else: print 'You have selected option 2'
    
    window = mc.window( w=150 )
    mc.columnLayout()
    mc.textFieldButtonGrp (l='option 1', bl='Set', ad3=2, bc=(lambda : testFunction('option1'))
    mc.textFieldButtonGrp (l='option 2', bl='Set', ad3=2, bc=(lambda : testFunction('option2'))
    mc.showWindow(window)
    

    There's a more detailed explanation of how to set up callbacks easily here.

    PS: Note the addition of the columnLayout command. Without it your controls will lay out on top of eachother