Create function for optionMenuGrp

175 views
Skip to first unread message

likage

unread,
Oct 13, 2014, 12:12:07 AM10/13/14
to python_in...@googlegroups.com
Is it possible to pass functions into Maya optionMenuGrp (combobox-alike)?

I have done up a simple UI where I have this combobox (maya cmds not PyQt) and there are 2 options in it.
However only then I realized that I am unable to 'call' out the function, nor are there any similar flags to it in its documentation (maybe there is but I do not know of it yet...)

I tried out using the following code but I was prompted with errors in the menuItem statements:
# Error: non-keyword arg after keyword arg
#   File "<maya console>", line 9
# SyntaxError: non-keyword arg after keyword arg #



Then I tried playing around with the placement of test1_func() or test2_func, it print out the statement as the code is executed but not executing it anymore if I tried to select the second menu item...

My code:
import maya.cmds as cmds

cmds
.window(w=150, h=100)
cmds
.columnLayout(adjustableColumn=True)
form
= cmds.formLayout(numberOfDivisions=100)
       
exportSelection
= cmds.optionMenuGrp(label=' Selection Options ', columnWidth=(1, 90))
test1
= cmds.menuItem(label='Export using item selection range', test1_func())
test2
= cmds.menuItem(test2_func(), label='Export using time slide range', test2_func())

startLbl
= cmds.text( label='Start' )
start
= cmds.textField(startLbl, w = 100, h = 20)

endLbl
= cmds.text( label='End' )
end = cmds.textField(endLbl, w = 100, h = 20)


cmds
.formLayout(form, edit=True, attachForm=[\
(exportSelection, 'top', 5),\
(exportSelection, 'left', 5),\

(startLbl, 'top', 40),\
(startLbl, 'left', 7),
(start, 'top', 35),\
(start, 'left', 45),

(endLbl, 'top', 60),\
(endLbl, 'left', 7),
(end, 'top', 60),\
(end, 'left', 45)])


def test1_func(*args):
   
print "option 1 is selected"

def test2_func(*args):
   
print "option 2 is selected"

cmds
.showWindow()


Justin Israel

unread,
Oct 13, 2014, 1:20:50 AM10/13/14
to python_in...@googlegroups.com

You are seeing that error because you are trying to pass a “non-keyword arg after keyword arg”:

test1 = cmds.menuItem(label='Export using item selection range', test1_func())

test2 = cmds.menuItem(test2_func(), label='Export using time slide range', test2_func())

When you start using keyword args (label=”foo”), you cannot then pass non-keyword args (x, y ,z)

In addition, you are actually executing your functions directly instead of trying to pass the reference to them:

# calling the function
foo(test2_func())
# passing a reference 
foo(test2_func)

With those issues aside, you should be able to just pass your function object directly to the command parameter for each menuItem:

test1 = cmds.menuItem(label="foo", command=test1_func)

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/64b66ab8-a585-4b25-8322-f62e431daced%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

likage

unread,
Oct 14, 2014, 2:56:08 AM10/14/14
to python_in...@googlegroups.com
I have kind of manage to get it to work.
This is actually an exporting object plugin but I have got 2 problems.
1. My initial window aren't popping up when I select my object >> File >> Export selection
2. Based on the selection, will it be possible for me to grab the different values based on the menu selection and used it in my __init__ function?



def __init__(self, transform, startAnimation, endAnimation, cameraObj):
       
       
self.fileExport = []
       
self.initialWindow()
       
        mayaGlobal
= OpenMaya.MGlobal()
        mayaGlobal
.viewFrame(OpenMaya.MTime(1))

       
for i in range(startAnimation, (endAnimation + 1)):

            focalLength
= cameraObj.focalLength()
           
            vFilmApp
= cameraObj.verticalFilmAperture()

            focalOut
= 2* math.degrees(math.atan(vFilmApp * 25.4/ (2* focalLength)))

            myEuler
= OpenMaya.MEulerRotation()
            spc
= OpenMaya.MSpace.kWorld

            trans
= transform.getTranslation(spc)

            rotation
= transform.getRotation(myEuler)
            rotVector
= OpenMaya.MVector(myEuler.asVector())

           
self.fileExport.append((str(i) + '\t' + str(trans[0]) + "\t" + str(trans[1]) + "\t" + str(trans[2]) + "\t" + str(math.degrees(rotVector[0])) + "\t" + str(math.degrees(rotVector[1])) + "\t" + str(math.degrees(rotVector[2])) + "\t" + str(focalOut) + "\n"))

            mayaGlobal
.viewFrame(OpenMaya.MTime(i+1))
           
           
   
def optionMenuCallback(*args):
        fn
= cmds.menuItem (args[0], q=True, c=True)
       
if fn:
            fn
()

   
def menu1Callback():
       
print 'menu 1 fired'
        startAnimation
= cmds.playbackOptions(query=True, minTime=True)
        endAnimation
= cmds.playbackOptions(query=True, maxTime=True)

   
def menu2Callback():
       
print 'menu 2 fired'
        startAnimation
= cmds.findKeyframe(which='first')
        endAnimation
= cmds.findKeyframe(which='last')


   
def initialWindow(self, *args):
        w
= cmds.window(w=150, h=100, title = "Export Selection" )
        cmds
.columnLayout(adjustableColumn=True)
        form
= cmds.formLayout(numberOfDivisions=100)
        exportSelection
= cmds.optionMenuGrp(label='example', cc=optionMenuCallback)
        test1
= cmds.menuItem('item1', c = menu1Callback)
        test1
= cmds.menuItem('item2', c= menu2Callback)
        cmds
.showWindow(w)

   
def __call__(self):
       
return self.fileExport


Justin Israel

unread,
Oct 14, 2014, 5:22:35 AM10/14/14
to python_in...@googlegroups.com
On Tue, Oct 14, 2014 at 7:56 PM, likage <dissid...@gmail.com> wrote:
I have kind of manage to get it to work.
This is actually an exporting object plugin but I have got 2 problems.
1. My initial window aren't popping up when I select my object >> File >> Export selection

Not sure from what you posted.
 
2. Based on the selection, will it be possible for me to grab the different values based on the menu selection and used it in my __init__ function?

Your constructor would have already run by the time your initialWindow() method would run, so I am not sure what you mean by your __init__ function having access to values based on menu selections. 

Also, your two menu callbacks are missing the "self, *args" params.
 

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

likage

unread,
Oct 14, 2014, 7:10:45 AM10/14/14
to python_in...@googlegroups.com
My reason for the optionMenu is so that User can choose between, to grab the frame range of the time slider, or to grab the 'keyframed' range of the selection (camera selection in this case).
As such, in the following code, it handles the exporting of camera, and I would say the main focus would be the startAnimation and endAnimation (dependable on which option the user choose)

This is the initial code before implementation.

def __init__(self, transform, startAnimation, endAnimation, cameraObj):
   
self.fileExport =[]

    mayaGlobal
= OpenMaya.MGlobal()
    mayaGlobal
.viewFrame(OpenMaya.MTime(1))

   
for i in range(startAnimation, (endAnimation + 1)):

        focalLength
= cameraObj.focalLength()
       
        vFilmApp
= cameraObj.verticalFilmAperture()

        focalOut
= 2* math.degrees(math.atan(vFilmApp * 25.4/ (2* focalLength)))

        myEuler
= OpenMaya.MEulerRotation()
        spc
= OpenMaya.MSpace.kWorld

        trans
= transform.getTranslation(spc)

        rotation
= transform.getRotation(myEuler)
        rotVector
= OpenMaya.MVector(myEuler.asVector())

       
self.fileExport.append((str(i) + '\t' + str(trans[0]) + "\t" + str(trans[1]) + "\t" + str(trans[2]) + "\t" + str(math.degrees(rotVector[0])) + "\t" + str(math.degrees(rotVector[1])) + "\t" + str(math.degrees(rotVector[2])) + "\t" + str(focalOut) + "\n"))


        mayaGlobal
.viewFrame(OpenMaya.MTime(i))

def __call__(self):
   
return self.fileExport

And so, I thought if I integrate in the optionMenu as I cited above, how can I make my __init__ function to recognize the values of the startAnimation and endAnimation based on the menu selection?

likage

unread,
Oct 14, 2014, 7:11:55 AM10/14/14
to python_in...@googlegroups.com
So are there any ways that I can run my initialwindow first before the __init__?

Justin Israel

unread,
Oct 15, 2014, 5:37:37 AM10/15/14
to python_in...@googlegroups.com

You may need to post more of your plugin (and also I probably have a lack of experience with the specific plugin type you are writing), but the structure seems strange to me. I wouldn't expect that you should be doing so much work within the constructor of the class. Is that how the plugin is meant to be written?
Ideally you would show a UI before the plugin executes, and then your plugin would run with the desired parameters being passed. It would be backwards to think that other methods of your class should run first and then supply information to your constructor.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

likage

unread,
Oct 15, 2014, 9:22:09 AM10/15/14
to python_in...@googlegroups.com
I am trying to tweak from a current script file, and as far as I know, when the plugin is loaded, user will just need to select the camera they would like to export (File>>Export selection) with format from the plugin -chan.

I will not be posting all the code, but the portions that are affilated with this exporting code. Hopefully it helps?

class customNodeTranslator(OpenMayaMPx.MPxFileTranslator):
   
def __init__(self):
       
OpenMayaMPx.MPxFileTranslator.__init__(self)
   
def haveWriteMethod(self):
       
return True
   
def haveReadMethod(self):
       
return True
   
def filter(self):
       
return "*.chan"
   
def defaultExtension(self):
       
return "chan"
   
def writer( self, fileObject, optionString, accessMode ):
       
try:
            fullName
= fileObject.fullName()
            fileHandle
= open(fullName,"w")


            selectList
= OpenMaya.MSelectionList()
   
           
OpenMaya.MGlobal.getActiveSelectionList(selectList)
            node
= OpenMaya.MObject()
            depFn
= OpenMaya.MFnDependencyNode()
            path
= OpenMaya.MDagPath()
            iterator
= OpenMaya.MItSelectionList(selectList)
           
            animationTime
= OpenMayaAnim.MAnimControl()
           
            maxTime
= int(animationTime.maxTime().value())
            minTime
= int(animationTime.minTime().value())
           
           
           
while (iterator.isDone() == 0):
               
               
                iterator
.getDependNode(node)
               
                depFn
.setObject(node)
               
                iterator
.getDagPath(path, node)
               
                cameraObject
= OpenMaya.MFnCamera(path)
               
                transform
= OpenMaya.MFnTransform(path)
               
                chanMe
= fileExporter(transform, minTime, maxTime, cameraObject)
               
...

               
...


class fileExporter():
   
""" module for exporting chan files from application. arguments: object, startFrame, endFrame """


    fileExport
= []



   
def __init__(self, transform, startAnimation, endAnimation, cameraObj):



        mayaGlobal
= OpenMaya.MGlobal()

Justin Israel

unread,
Oct 15, 2014, 4:05:46 PM10/15/14
to python_in...@googlegroups.com
Oh ok. This make a little more sense now. I can see that your fileExporter is a completely custom class and has nothing to do with the actual plugin class. What you probably want to do is to move your logic that is in your __init__ into another method. Your writer plugin can then create an instance of the FileExplorer, and have it show the UI. Then it can take the values from the UI and call another method that actually does the work. Your constructor shouldn't be doing all the work. 

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

likage

unread,
Oct 16, 2014, 5:32:01 AM10/16/14
to python_in...@googlegroups.com
I am slowly trying to integrate parts by parts as I played and test around with it.
However, I have a questions.

Seeing that I have 2 menu options, while it is possible for me to create functions individually for each of the menu option, I am trying to add on a button in which it will fire the final confirmation when User clicks onto it. And hence, I would like to ask how do I 'capture' the info of the menu selection?

Justin Israel

unread,
Oct 16, 2014, 5:54:43 AM10/16/14
to python_in...@googlegroups.com

Did you have a look at the documentation?
http://download.autodesk.com/us/maya/2011help/CommandsPython/optionMenuGrp.html#flagchangeCommand

You can attach a callback to the changeCommand and then use a query flag to get the value of the optionMenuGrp selected item. The callback may pass you the selected value but I don't remember

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

likage

unread,
Oct 17, 2014, 4:54:30 AM10/17/14
to python_in...@googlegroups.com
Okay, I think I have switched it to the use of checkboxes, as it seems slightly easier for me?

Pardon my lack of understanding, but I was wondering if you could further elaborate second previous post - move your logic that is in your __init__ into another method. Your writer plugin can then create an instance of the FileExplorer, and have it show the UI. Then it can take the values from the UI and call another method that actually does the work. Your constructor shouldn't be doing all the work.

Apparently in my current code, the file gets exported before my UI, way before I can choose between the options/functions I have set it in my checkBox (and the okayBtn)


import math, sys, string, os

import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.OpenMayaAnim as OpenMayaAnim

import maya.cmds as cmds
import maya.mel as mel

kPluginTranslatorTypeName
= "chan Export/Import"
kVersionNumber
= "0.5a"

camSel
= []
start
= []
end = []
win_name
= "chan_window"

class CustomNodeTranslator(OpenMayaMPx.MPxFileTranslator):  
   
def __init__(self):

       
OpenMayaMPx.MPxFileTranslator.__init__(self)      
   
def haveWriteMethod(self):
       
return True
   
def haveReadMethod(self):
       
return True
   
def filter(self):
       
return "*.chan"
   
def defaultExtension(self):
       
return "chan"
   
def writer( self, fileObject, optionString, accessMode ):

       
       
self.exportWin()

       
       
try:
                       
            fullName
= fileObject.fullName()
            fileHandle
= open(fullName,"w")

            selectList
= OpenMaya.MSelectionList()
   
           
OpenMaya.MGlobal.getActiveSelectionList(selectList)
            node
= OpenMaya.MObject()
            depFn
= OpenMaya.MFnDependencyNode()
            path
= OpenMaya.MDagPath()
            iterator
= OpenMaya.MItSelectionList(selectList)
           
            animationTime
= OpenMayaAnim.MAnimControl()
           
            maxTime
= int(animationTime.maxTime().value())
            minTime
= int(animationTime.minTime().value())
           
           
while (iterator.isDone() == 0):
               
                iterator
.getDependNode(node)
               
                depFn
.setObject(node)
               
                iterator
.getDagPath(path, node)
               
                cameraObject
= OpenMaya.MFnCamera(path)
               
                transform
= OpenMaya.MFnTransform(path)
                   
                chanMe
= fileExporter(transform, minTime, maxTime, cameraObject)

           
               
for all in chanMe():
                    fileHandle
.write(all)
                   
                iterator
.next()
           
            fileHandle
.close()
           
       
except:
            sys
.stderr.write( "Failed to write file information\n")
           
raise


   
   
def test1On(self, *args):
       
print "User checked option1"
        cmds
.checkBox(self.chk2, edit = True, enable = False)

       
        startAnimation
= cmds.playbackOptions(query=True, minTime=True)
        endAnimation
= cmds.playbackOptions(query=True, maxTime=True)

       
        start
.append(startAnimation)
       
end.append(endAnimation)
   
   
def test1Off(self, *args):
       
print "User un-checked option1"
        cmds
.checkBox(self.chk2, edit = True, enable = True)
       
del start[:]
       
del end[:]
       
   
def test2On(self, *args):
       
print "User checked option2"
        cmds
.checkBox(self.chk1, edit = True, enable = False)

       
        startAnimation
= cmds.findKeyframe(which='first')
        endAnimation
= cmds.findKeyframe(which='last')


        start
.append(startAnimation)
       
end.append(endAnimation)

   
def test2Off(self, *args):
       
print "User un-checked option2"
        cmds
.checkBox(self.chk1, edit = True, enable = True)
       
del start[:]
       
del end[:]

   
def test3(self, *args):
        chkVal1
= cmds.checkBox(self.chk1, query=True, value=True)
        chkVal2
= cmds.checkBox(self.chk2, query=True, value=True)
       
       
if chkVal1 == 1:
           
print "opt1 Pressed!"      
           
print start
           
print end
           
       
elif chkVal2 == 1:
           
print "opt2 Pressed!"
           
print start
           
print end
           
       
else:
            cmds
.warning("Check an option")

   
def exportWin(self):

        w
= cmds.window(w=150, h=100, title = "Export Selection" )
        cmds
.columnLayout( adjustableColumn=True )
        form
= cmds.formLayout(numberOfDivisions=100)

       
self.chk1 = cmds.checkBox( label='option1', onc = self.test1On, ofc = self.test1Off )
       
self.chk2 = cmds.checkBox( label='option2', onc = self.test2On, ofc = self.test2Off )
       
self.okayBtn = cmds.button(label='okay!', command=self.test3, width=150, height=35)
               

        cmds
.formLayout(form, edit=True, attachForm=[\
       
(self.chk1, 'top', 15),\
       
(self.chk1, 'left', 15),\
       
(self.chk2, 'top', 30),\
       
(self.chk2, 'left', 15),\
       
(self.okayBtn, 'top', 50),\
       
(self.okayBtn, 'left', 15)])

        cmds
.showWindow( w )    
       
   
   
def processLine( self, lineStr ):

       
self.importTheChan.writeFrameData(lineStr)
       
   
def reader(self, fileObject, optionString, accessMode):
       
self.initialWindow()
       
try:
           
# Empty out any existing captured info in camSel list to have a clean import
            camSelClear
= camSel
           
del camSelClear[:]
           
            fullPath
= fileObject.fullName()
         
           
self.fileHandle = open(fullPath,"r")
            camHandle
= self.fileHandle
           
            camBaseName
= os.path.basename(camHandle.name)
            camName
= os.path.splitext(camBaseName)[0]
           
           
# Imported camera will not have any animation unless Rotation Order is selected
            cameraName
, cameraShape =  cmds.camera(n=str(camName))
            camSel
.extend((cameraName, cameraShape))

            cmds
.scale(0.5, 0.5, 0.5)
           
       
except:
            sys
.stderr.write( "Failed to read file information\n")
           
raise
       
       
self.fileObject = fileObject
       
self.optionString = optionString
       
self.accessMode = accessMode
       
       
class fileExporter():
   
""" module for exporting chan files from application. arguments: object, startFrame, endFrame """

   
   
def __init__(self, transform, startAnimation, endAnimation, cameraObj):
       
       
print ">>> Exporting..."

       
       
self.fileExport = []

        mayaGlobal
= OpenMaya.MGlobal()
        mayaGlobal
.viewFrame(OpenMaya.MTime(1))

       
       
# Capture the animation keyframes within the selection instead of the range from time slider
       
#startAnimation = cmds.findKeyframe(which='first')
       
#endAnimation = cmds.findKeyframe(which='last')

       
# Converts the float arguement into integer
       
for i in range(int(startAnimation), int(endAnimation + 1)):


            focalLength
= cameraObj.focalLength()
           
            vFilmApp
= cameraObj.verticalFilmAperture()

            focalOut
= 2* math.degrees(math.atan(vFilmApp * 25.4/ (2* focalLength)))

            myEuler
= OpenMaya.MEulerRotation()
            spc
= OpenMaya.MSpace.kWorld

            trans
= transform.getTranslation(spc)

            rotation
= transform.getRotation(myEuler)
            rotVector
= OpenMaya.MVector(myEuler.asVector())

           
self.fileExport.append((str(i) + '\t' + str(trans[0]) + "\t" + str(trans[1]) + "\t" + str(trans[2]) + "\t" + str(math.degrees(rotVector[0])) + "\t" + str(math.degrees(rotVector[1])) + "\t" + str(math.degrees(rotVector[2])) + "\t" + str(focalOut) + "\n"))


            mayaGlobal
.viewFrame(OpenMaya.MTime(i+1))

   
def __call__(self):
       
return self.fileExport

   
def radianToDegree(self, radians):
        outDegrees
= 0.0
        outDegrees
= (float(radians) / (math.pi))*180
       
return outDegrees


# creator
def translatorCreator():
   
return OpenMayaMPx.asMPxPtr( CustomNodeTranslator() )

# initialize the script plug-in
def initializePlugin(mobject):
    mplugin
= OpenMayaMPx.MFnPlugin(mobject)

   
try:
        mplugin
.registerFileTranslator(kPluginTranslatorTypeName, None, translatorCreator)
   
except:
        sys
.stderr.write( "Failed to register translator: %s" % kPluginTranslatorTypeName )
       
raise

# uninitialize the script plug-in
def uninitializePlugin(mobject):
    mplugin
= OpenMayaMPx.MFnPlugin(mobject)
   
try:
        mplugin
.deregisterFileTranslator( kPluginTranslatorTypeName )
   
except:
        sys
.stderr.write( "Failed to deregister translator: %s" % kPluginTranslatorTypeName )
       
raise


Justin Israel

unread,
Oct 17, 2014, 6:26:21 AM10/17/14
to python_in...@googlegroups.com

I'm pretty sure it is because you are calling showWindow() in your exportWin, which shows the dialog but does not block. So the rest of your export happens right away.
What you probably want to do is one of two options:

Either have exportWin be the last line of your writer method, and allow it to actually trigger the export command when the user accepts the dialog

Or use a layoutDialog to launch your UI so that it actually blocks. Then it can collect your options, and continue in the writer method with your parameters.

In both of these cases, the fact that you are doing all of your work within the constructor of your fileExport class isn't really related. The problem at this stage is that you are immediately jumping past your shown dialog.

...

likage

unread,
Oct 17, 2014, 6:44:25 AM10/17/14
to python_in...@googlegroups.com
sorry, by shown dialog, do you mean to say the exportWin?

Justin Israel

unread,
Oct 17, 2014, 6:49:46 AM10/17/14
to python_in...@googlegroups.com

Your exportWin function creates a window and shows it,  right? Once that window is shown, your exportWin will return and the execution will continue through the rest of your writer. I think you are thinking the window should wait to collect input, but it does not.
If you want to use a dialog to collect input then you have to somehow wait until the input is collected before the rest of the writer logic occurs

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

likage

unread,
Oct 20, 2014, 7:20:41 AM10/20/14
to python_in...@googlegroups.com
This may not be my best attempt but I would like to get some pointers if there are any.
I tried to break up the exporting code, in hope that it may be easier, but I am getting errors in line 150 - # NameError: global name 'transform' is not defined # but if I am going to edit line 56 - chanMe = fleExporter.actualExp(transform, minTime, maxTime, cameraObject), I will get this error - // Error: line 0: unbound method actualExp() must be called with ChanFileExporter instance as first argument (got MFnTransform instance instead)


import math, sys, string, os

import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.OpenMayaAnim as OpenMayaAnim

import maya.cmds as cmds
import maya.mel as mel

kPluginTranslatorTypeName
= "chan Export/Import"
kVersionNumber
= "0.5a"

class CustomNodeTranslator(OpenMayaMPx.MPxFileTranslator):  
   
def __init__(self):
       
OpenMayaMPx.MPxFileTranslator.__init__(self)      
   
def haveWriteMethod(self):
       
return True
   
def haveReadMethod(self):
       
return True
   
def filter(self):
       
return "*.chan"
   
def defaultExtension(self):
       
return "chan"
   
def writer( self, fileObject, optionString, accessMode ):

       
try:
                       
            fullName
= fileObject.fullName()
            fileHandle
= open(fullName,"w")

            selectList
= OpenMaya.MSelectionList()
   
           
OpenMaya.MGlobal.getActiveSelectionList(selectList)
            node
= OpenMaya.MObject()
            depFn
= OpenMaya.MFnDependencyNode()
            path
= OpenMaya.MDagPath()
            iterator
= OpenMaya.MItSelectionList(selectList)
           
            animationTime
= OpenMayaAnim.MAnimControl()
           
            maxTime
= int(animationTime.maxTime().value())
            minTime
= int(animationTime.minTime().value())
           
           
while (iterator.isDone() == 0):
               
                iterator
.getDependNode(node)
               
                depFn
.setObject(node)
               
                iterator
.getDagPath(path, node)
               
                cameraObject
= OpenMaya.MFnCamera(path)
               
                transform
= OpenMaya.MFnTransform(path)

                   
                chanMe
= fleExporter(transform, minTime, maxTime, cameraObject)

           
               
for all in chanMe():
                    fileHandle
.write(all)
                   
                iterator
.next()
           
            fileHandle
.close()
           
       
except:
            sys
.stderr.write( "Failed to write file information\n")
           
raise

   
   
def processLine( self, lineStr ):

       
self.importTheChan.writeFrameData(lineStr)
       

class fileExporter():

   
def __init__(self, transform, startAnimation, endAnimation, cameraObj):

       
self.start = ""
       
self.end = ""
       
self.fileExport = []
       
self.exportWin()

   
def exportWin(self):
       
print ">>> Running Exporting UI"
       
       
self.expWindow = cmds.window(w=150, h=100, title = "Export Selection" )

        cmds
.columnLayout( adjustableColumn=True )
        form
= cmds.formLayout(numberOfDivisions=100)

        cmds
.radioCollection()
       
self.chk1 = cmds.radioButton( label='option1', onc = self.opt1On, ofc = self.opt1Off )
       
self.chk2 = cmds.radioButton( label='option2', onc = self.opt2On, ofc = self.opt2Off )
       
self.okayBtn = cmds.button(label='okay!', command=self.runSel, width=150, height=35)


        cmds
.formLayout(form, edit=True, attachForm=[\
       
(self.chk1, 'top', 15),\
       
(self.chk1, 'left', 15),\
       
(self.chk2, 'top', 30),\
       
(self.chk2, 'left', 15),\
       
(self.okayBtn, 'top', 50),\
       
(self.okayBtn, 'left', 15)])


        cmds
.showWindow( self.expWindow )
   
   
def opt1On(self, *args):
       
print "User checked option1"

        startAnimation
= cmds.playbackOptions(query=True, minTime=True)
        endAnimation
= cmds.playbackOptions(query=True, maxTime=True)

       
       
self.start = startAnimation
       
self.end = endAnimation
   
   
def opt1Off(self, *args):
       
print "User un-checked option1"
        cmds
.radioButton(self.chk2, edit = True, enable = True)
       
self.start = ""
       
self.end = ""
       
   
def opt2On(self, *args):
       
print "User checked option2"

        startAnimation
= cmds.findKeyframe(which='first')
        endAnimation
= cmds.findKeyframe(which='last')


       
self.start = startAnimation
       
self.end = endAnimation

   
def opt2Off(self, *args):
       
print "User un-checked option2"
       
self.start = ""
       
self.end = ""

   
def runSel(self, *args):
        chkVal1
= cmds.radioButton(self.chk1, query=True, sl=1)
        chkVal2
= cmds.radioButton(self.chk2, query=True, sl=1)

       
       
if chkVal1 == 1:
           
print "opt1 Pressed!"
     
           
print self.start
           
print self.end
           
self.test()

           
       
elif chkVal2 == 1:
           
print "opt2 Pressed!"

           
print self.start
           
print self.end
           
self.test()

           
       
else:
            cmds
.warning("Check an option")


   
   
def test(self):
       
# NameError: global name 'transform' is not defined #
       
self.actualExp(transform, self.start, self.end, cameraObj)
   
   
   
def actualExp(self, transform, startAnimation, endAnimation, cameraObj):
        mayaGlobal
= OpenMaya.MGlobal()
        mayaGlobal
.viewFrame(OpenMaya.MTime(1))

       
# Converts the float arguement into integer

        sys
.stderr.write( "Failed to deregister translator: %s" % kPluginTranslatorTypeName )
       
raise



Justin Israel

unread,
Oct 20, 2014, 2:32:32 PM10/20/14
to python_in...@googlegroups.com

This should be a pretty easy fix. In your constructor to the fileExporter class, you accept 4 arguments, but you don't save any of them, so they are lost:

#---------
class fileExporter():

    def __init__(self, transform, startAnimation, endAnimation, cameraObj):
        self.start = ""
        self.end = ""
        self.fileExport = []
        self.exportWin()

#---------

But if you saved them, then your gui can still update some of them, and, you will have saved the transform to reference later:

#---------
class fileExporter():

    def __init__(self, transform, startAnimation, endAnimation, cameraObj):

        self.transform = transform


        self.start = startAnimation
        self.end = endAnimation

        self.cameraObj = cameraObj
        self.fileExport = []
        self.exportWin()
    ...
    def test(self):
        self.actualExp(self.transform, self.start, self.end, self.cameraObj)
#---------

Once you had fixed the transform, you would have seen the same error about the cameraObj

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

likage

unread,
Oct 21, 2014, 6:34:43 AM10/21/14
to python_in...@googlegroups.com
Thanks, turns out I also need to retweak a few stuff in my other functions.

However, while the information capturing and all seems to be working, rather I got issues with the exporting.
It does creates a file but it is of zero bytes size and I noticed that the following function wasn't exactly being used in any events

I tried adding it into the __init__, though it is 'reading' but it is not doing much of anything...

def __call__(self):
        return self.fileExport

Justin Israel

unread,
Oct 21, 2014, 2:37:08 PM10/21/14
to python_in...@googlegroups.com

I don't see in your last example where your custom fileExporter class supports iteration, where you loop over it and write something to a file. Seems your example contains bits and pieces of things that are either not used or not defined.

What are you expecting retuning that self.fileExport to do?

Your question is unclear.

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.

likage

unread,
Oct 22, 2014, 1:37:48 AM10/22/14
to python_in...@googlegroups.com
Well, I did not change any of the code that it has initially.
I only added in more of the maya cmds into the exporting class. Likewise, the __call__ was part of the original code as well.

As for self.fileExport, it will writes in the (animation) data - depending on the selection, and it is suppose to write the said data onto the .text file as the export selection is used.

On Wednesday, October 22, 2014 2:37:08 AM UTC+8, Justin Israel wrote:

I don't see in your last example where your custom fileExporter class supports iteration, where you loop over it and write something to a file. Seems your example contains bits and pieces of things that are either not used or not defined.

What are you expecting retuning that self.fileExport to do?

Your question is unclear.

On 21/10/2014 11:34 PM, "likage" <dissid...@gmail.com> wrote:
Thanks, turns out I also need to retweak a few stuff in my other functions.

However, while the information capturing and all seems to be working, rather I got issues with the exporting.
It does creates a file but it is of zero bytes size and I noticed that the following function wasn't exactly being used in any events

I tried adding it into the __init__, though it is 'reading' but it is not doing much of anything...

def __call__(self):
        return self.fileExport

--
You received this message because you are subscribed to the Google Groups "Python Programming for Autodesk Maya" group.
To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_maya+unsub...@googlegroups.com.

Justin Israel

unread,
Oct 22, 2014, 2:59:08 AM10/22/14
to python_in...@googlegroups.com

I don't know man. If you want to post another full updated version  of your code on pastebin and point out lines, I am sure someone will take a look. But I don't think you will get much more detailed help at this point because no one really knows your code but you.

To unsubscribe from this group and stop receiving emails from it, send an email to python_inside_m...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/python_inside_maya/cb22bc6a-4a69-4cab-9327-134fc78a737f%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages