(Maya Python) Как запустить переключатели через функцию графического интерфейса?

Обычно, когда я запускаю скрипт с параметрами переключателя, вы выбираете параметр переключателя, а затем активируете его с помощью кнопки. Раньше я оставлял свой графический интерфейс меню вне функции: но с тех пор, как я научился импортировать сценарии Maya, я начал оборачивать свои интерфейсы меню в функцию графического интерфейса, что означает, что моя техника переключателей больше не работает. Я понятия не имею, как заставить его работать. Сам сценарий достаточно прост: просто выберите параметр переключателя после импорта сценария, а затем создайте фигуру с помощью кнопки: по крайней мере, так это ДОЛЖНО работать. Вместо этого я не получаю никаких ошибок и форм, и я не знаю, что сломано.

'''
import cubeTestTemp
reload (cubeTestTemp)
cubeTestTemp.gui()
'''

import maya.cmds as cmds

#Creates ui. 
if cmds.window("cubeWin", exists =True):
    cmds.deleteUI("cubeWin", window = True)

myWindow = cmds.window("cubeWin",t='DS shapeDemo V1',w=200, h=500, toolbox=True)
column = cmds.columnLayout(adj=True)
#Creates variable to indicate the check box status. 1=Checked 0=Not Checked. 

cubeNum1 = 0
cubeNum2 = 0


#Creates Button funtion. 
def defaultButtonPush(*args):
       #The Print checks if button is pushed and what is the check box status. 
       print "Button is pushed."
       print cubeNum1
       #Check box argument finds the status of the variable and determines what to do. 
       #Eather create a cube or display a error dialog box.
       if cubeNum1 == 1:
        print "Cube Creation sucessful"
        cmds.polyCube()

       print "Button is pushed."
       print cubeNum2
       if cubeNum2 == 1:
        print "Sphere Creation sucessful"
        cmds.polySphere()


def gui(*args):
    #Creates check box. 
    #In the onCommand Script (onc) and offCommand Script (ofc) flags all commands must be made in between double quotes.
    cmds.radioCollection()
    cmds.radioButton(label='Cube',align='left',onCommand="cubeNum1 = 1", offCommand="cubeNum1 = 0")
    cmds.radioButton(label='Sphere',align='left',onCommand="cubeNum2 = 1", offCommand="cubeNum2 = 0")
    #Creates Button.
    cmds.button( label='Execute', command=defaultButtonPush ,align='left' )

cmds.showWindow()

person Dasteel    schedule 10.02.2020    source источник
comment
вместо лямбда в ответе @ababak вы можете использовать частичное: stackoverflow.com/questions/48570602/   -  person DrWeeny    schedule 11.02.2020


Ответы (1)


Вот модифицированный скрипт. Проблема заключалась в объеме сценариев. «onCommand» выполнялся в своей собственной области видимости, имеющей собственные переменные «cubeNum».

"""
import cubeTestTemp
reload (cubeTestTemp)
cubeTestTemp.gui()
"""

import maya.cmds as cmds

# Variable to indicate the radio button status. 1=Cube, 2=Shpere. 
shape_selector = 0


def action_button(*args):
    """
    Create an object based on the shape_selector status
    """
    print "Button is pushed", repr(args)
    if shape_selector == 1:
        cmds.polyCube()
        print "Cube created"
    elif shape_selector == 2:
        cmds.polySphere()
        print "Sphere created"
    else:
        print "No shape selected"


def selection_changed(shape):
    """
    Save the current shape selection
    into global variable "shape_selector"
    """
    global shape_selector
    shape_selector = shape
    print "Current selection:", shape_selector


def gui():
    """
    Create the GUI
    """
    if cmds.window("cubeWin", exists=True):
        cmds.deleteUI("cubeWin", window=True)
    myWindow = cmds.window("cubeWin", t='DS shapeDemo V1', w=200, h=500, toolbox=True)
    column = cmds.columnLayout(adj=True)
    # Create the radio buttons 
    cmds.radioCollection()
    cmds.radioButton(label='Cube',align='left', select=True, onCommand=lambda x:selection_changed(1))
    cmds.radioButton(label='Sphere',align='left', onCommand=lambda x:selection_changed(2))
    # Create the push button
    cmds.button(label='Create', command=action_button, align='left')
    cmds.showWindow()

if __name__ == "__main__":
    gui()

Другой способ - прочитать состояние переключателя только при необходимости.

"""
import cubeTestTemp
reload (cubeTestTemp)
cubeTestTemp.gui()
"""

import maya.cmds as cmds


def action_button(cube_button, sphere_button):
    """
    Create an object based on the shape_selector status
    """
    if cmds.radioButton(cube_button, query=True,select=True):
        cmds.polyCube()
        print "Cube created"
    elif cmds.radioButton(sphere_button, query=True,select=True):
        cmds.polySphere()
        print "Sphere created"
    else:
        print "No shape selected"


def gui():
    """
    Create the GUI
    """
    if cmds.window("cubeWin", exists=True):
        cmds.deleteUI("cubeWin", window=True)
    myWindow = cmds.window("cubeWin", t='DS shapeDemo V1', w=200, h=500, toolbox=True)
    column = cmds.columnLayout(adj=True)
    # Create the radio buttons 
    cmds.radioCollection()
    # Save the button ids
    cube_button = cmds.radioButton(label='Cube',align='left', select=True)
    sphere_button = cmds.radioButton(label='Sphere',align='left')
    # Create the push button
    cmds.button(label='Create', command=lambda x:action_button(cube_button, sphere_button), align='left')
    cmds.showWindow()

if __name__ == "__main__":
    gui()
person ababak    schedule 10.02.2020
comment
Большое спасибо, ababak, но у меня есть еще несколько вопросов. Допустим, я хотел добавить третью кнопку-переключатель. Способен ли метод кодирования if elif сделать больше кнопок-переключателей или максимальное количество кнопок равно 2? - person Dasteel; 11.02.2020
comment
а затем мой следующий вопрос: что если name == main, что это за кодовый термин и что он делает? Комментарий, кажется, отредактировал символы подчеркивания: но я говорю об основной строке под функцией Gui. - person Dasteel; 12.02.2020
comment
Если вы довольны ответом на свой первоначальный вопрос, вы можете принять его;) - person ababak; 12.02.2020