[Python] Calling button commands from modules


#1

I’m somewhat new to python.
I’m experimenting with modules and am trying to do something pretty basic. A window, with a button, and when that button is pressed, something is printed to the console. Now, I know how to do that, but in this case, I’m trying to split it up into modules.
A script (we’ll call it script x) containing the function that takes an argument and prints it.
A window script that imports script x, creates a window with a button, and that button’s command is to run the imported script x.
And finally, a script that simply launches the whole process by importing the windows script, and passes it an argument which it in turns passes to script x.

Here it is -
testing\utilities\func.py:

import maya.cmds as cmds

def command(message):
    print(message)

testing\windows\win.py

import maya.cmds as cmds
import testing.utilities.func as func
reload(func)

def createWindow(message):
            
    if cmds.window('myWindow', exists=True):
            cmds.deleteUI('myWindow')
    win = cmds.window("myWindow")
    cmds.formLayout()
    cmds.button(label='execute', command=buttonCommand(message))
    cmds.showWindow(win)

def buttonCommand(message):
    func.command(message)

testing\launcher\launch.py

import maya.cmds as cmds
import testing.windows.win as win
reload(win)

win.createWindow('Hello, world!')

When I run launch.py, the window is created, button and all, but when I press the button I’m told that buttonCommand() is not defined.
I assume that is because it’s in it’s own imported script, and python is trying to find buttonCommand() in the namespace of launch.py
if that’s the case, one solution I could think of (as in, I’ve tried it, and it works) is to pass the ‘win.’ namespace as a variable, and then place that variable in front of buttonCommand().
But that seems like a clunky solution. There must surely be another way.
Can anyone help me?


#2

Hey, I see this was posted a few weeks ago, but if you haven’t figured it out, your best bet is to wrap the whole thing in a class. Function names are bound to their own modules and won’t carry over across importing. If you place the whole thing in a class, you can then access any of those functions through methods instead.