Maya python UI - local variable not defined error when used inside button command within same function

跟風遠走 提交于 2019-12-02 09:14:33
theodox

When you run the first sample in the listener, foo is defined in the global scope so it's available when the callback fires. In the second example it's defined in the scope of the function -- so it's not available when the callback fires in the global scope.

This will work:

import maya.cmds as cmds

def buildIt():
    cmds.window(title='Basic UI')
    cmds.columnLayout()
    foo = 'bar'
    def print_foo(*_):
        print foo
    cmds.button(label = 'foobar', command = print_foo)

    cmds.showWindow()

buildIt()

The difference here is that we pass the function print_foo directly, not as a string. So, Maya captures its value when the button is created and saves it (this is known as a closure, and it's super useful). This ensures that the function can be used when the callback is actually used.

In general, avoid using the string version of callbacks -- they are a holdover from MEL and they always result in exactly the problem you're seeing.

More detail here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!