Maya Python: выбор OptionMenu с помощью кнопки

Я новичок в python в Maya и пытаюсь создать пользовательский интерфейс, который может генерировать фигуры и преобразовывать их. Проблема, я думаю, заключается в функции ObjectCreation, но я не уверен. Пока это то, что у меня есть:

import maya.cmds as cmds

#check to see if window exists
if cmds.window("UserInterface", exists = True):
    cmds.deleteUI("UserInterface")
#create actual window
UIwindow = cmds.window("UserInterface", title = "User Interface Test", w = 500, h = 700, mnb = False, mxb = False, sizeable = False)
mainLayout = cmds.columnLayout(w = 300, h =500)

def SceneClear(*args):
    cmds.delete(all=True, c=True) #Deletes all objects in scene
cmds.button(label = "Reset", w = 300, command=SceneClear)

polygonSelectMenu = cmds.optionMenu(w = 250, label = "Polygon Selection:")
cmds.menuItem(label = " ")
cmds.menuItem(label = "Sphere")
cmds.menuItem(label = "Cube")
cmds.menuItem(label = "Cylinder")
cmds.menuItem(label = "Cone")

def ObjectCreation(*args):
    if polygonSelectMenu.index == 2: #tried referring to index
        ma.polySphere(name = "Sphere")
    elif polygonSelectMenu == "Cube":
        ma.polyCube(name = "Cube")
    elif polygonSelectMenu == "Cylinder":
        ma.polyCylinder(name = "Cylinder")
    elif polygonSelectMenu == "Cone":
        ma.polyCone(name = "Cone")
cmds.button(label = "Create", w = 200, command=ObjectCreation)

def DeleteButton(*args):
    cmds.delete()
cmds.button(label = "Delete", w = 200, command=DeleteButton)#Deletes selected object   

cmds.showWindow(UIwindow) #shows window

Мне нужно, чтобы пользователь выбрал один из параметров в меню параметров, а затем нажал кнопку «Создать», чтобы создать эту форму. Я пытался обратиться к нему по имени и индексу, но я не знаю, что мне не хватает. Как я уже сказал, я новичок в python, поэтому, когда я пытался найти ответ сам, я ничего не мог найти, а когда я нашел что-то похожее, я не мог этого понять. Кроме того, по какой-то причине функция SceneClear / кнопка сброса не работает, поэтому, если есть ответ на этот вопрос, сообщите мне.


person Luke Eccles    schedule 03.03.2015    source источник
comment
Чтобы добавить к ответу @DrHaze, пересмотрите имена своих функций. Вот рекомендация Python (PEP8): python.org/dev/peps /pep-0008/#названия-функций   -  person kartikg3    schedule 04.03.2015


Ответы (2)


polygonSelectMenu содержит путь к вашему optionMenu элементу пользовательского интерфейса. В моем случае это: UserInterface|columnLayout7|optionMenu4. Это просто строка, а не ссылка на элемент пользовательского интерфейса.

Чтобы получить доступ к его текущему значению, вы должны использовать это:

currentValue = cmds.optionMenu(polygonSelectMenu, query=True, value=True)

Все флаги optionMenu перечислены здесь (документ по командам Maya 2014) рядом с запрашиваемыми есть маленький зеленый Q.


В результате вот ваша функция ObjectCreation(*args):

def ObjectCreation(*args):
    currentValue = cmds.optionMenu(polygonSelectMenu, query=True, value=True)
    if currentValue == "Sphere": #tried referring to index
        cmds.polySphere(name = "Sphere")
    elif currentValue == "Cube":
        cmds.polyCube(name = "Cube")
    elif currentValue == "Cylinder":
        cmds.polyCylinder(name = "Cylinder")
    elif currentValue == "Cone":
        cmds.polyCone(name = "Cone")

Не по теме:

Избегайте объявления функций между строками кода (в вашем случае код создания пользовательского интерфейса), попробуйте вместо этого поместить код создания пользовательского интерфейса внутрь функции и вызвать эту функцию в конце вашего скрипта.

Это читабельно, так как у вас сейчас всего несколько элементов пользовательского интерфейса. Но как только вы начнете иметь 20 или более кнопок/меток/вводов, это может быстро привести к беспорядку.

Кроме того, я предпочитаю давать имя объекта элементам пользовательского интерфейса, как вы сделали с окном ("UserInterface"). Чтобы дать вам конкретный пример: cmds.optionMenu("UI_polygonOptionMenu", w = 250, label = "Polygon Selection:") Затем этот optionMenu может быть доступен в любом месте вашего кода, используя: cmds.optionMenu("UI_polygonOptionMenu", query=True, value=True)

Вот полностью модифицированный скрипт, если хотите:

import maya.cmds as cmds

def drawUI(): #Function that will draw the entire window
    #check to see if window exists
    if cmds.window("UI_MainWindow", exists = True):
        cmds.deleteUI("UI_MainWindow")
    #create actual window
    cmds.window("UI_MainWindow", title = "User Interface Test", w = 500, h = 700, mnb = False, mxb = False, sizeable = False)
    cmds.columnLayout("UI_MainLayout", w = 300, h =500)

    cmds.button("UI_ResetButton", label = "Reset", w = 300, command=SceneClear)

    cmds.optionMenu("UI_PolygonOptionMenu", w = 250, label = "Polygon Selection:")
    cmds.menuItem(label = " ")
    cmds.menuItem(label = "Sphere")
    cmds.menuItem(label = "Cube")
    cmds.menuItem(label = "Cylinder")
    cmds.menuItem(label = "Cone")

    cmds.button("UI_CreateButton", label = "Create", w = 200, command=ObjectCreation)
    cmds.button("UI_DeleteButton", label = "Delete", w = 200, command=DeleteButton)#Deletes selected object   

    cmds.showWindow("UI_MainWindow") #shows window

def SceneClear(*args):
    cmds.delete(all=True, c=True) #Deletes all objects in scene

def ObjectCreation(*args):
    currentValue = cmds.optionMenu("UI_PolygonOptionMenu", query=True, value=True)
    if currentValue == "Sphere": 
        cmds.polySphere(name = "Sphere")
    elif currentValue == "Cube":
        cmds.polyCube(name = "Cube")
    elif currentValue == "Cylinder":
        cmds.polyCylinder(name = "Cylinder")
    elif currentValue == "Cone":
        cmds.polyCone(name = "Cone")

def DeleteButton(*args):
    cmds.delete()

drawUI() #Calling drawUI now at the end of the script

Надеюсь, что это поможет вам.

person DrHaze    schedule 03.03.2015
comment
черт, ты добавил свой ответ примерно за пять секунд до того, как я добавил свой. Редкий вопрос двухчасовой давности! - person mhlester; 03.03.2015
comment
Большое спасибо :) Я начал сходить с ума от этого :p - person Luke Eccles; 03.03.2015
comment
Очень красиво ответил. Отличная дополнительная информация. - person kartikg3; 04.03.2015

как сказано выше, maya.cmds работает очень похоже на mel, и вы должны использовать команду cmds.optionMenu() с polygonSelectMenu в качестве первого аргумента.

В качестве альтернативы, если вы используете pymel вместо этого, вы можете получить доступ к атрибутам класса polygonSelectMenu с помощью оператора точки, например:

import pymel.core as pm

if pm.window("UserInterface", exists = True):
    pm.deleteUI("UserInterface")

UIwindow = pm.window("UserInterface", title = "User Interface Test", w = 500, h = 700, mnb = False, mxb = False, sizeable = False)
mainLayout = pm.columnLayout(w = 300, h =500)
polygonSelectMenu = pm.optionMenu(w = 250, label = "Polygon Selection:")
pm.menuItem(label = " ")
pm.menuItem(label = "Sphere")
pm.menuItem(label = "Cube")
pm.menuItem(label = "Cylinder")
pm.menuItem(label = "Cone")
pm.button(label = "Create", w = 200, command=ObjectCreation)
UIwindow.show()


def ObjectCreation(*args):
    print polygonSelectMenu.getValue()

также вы можете превратить программу в класс с помощью метода drawUI, что может упростить такие вещи, как хранение всех элементов, которые вы создаете в ObjectCreation, внутри атрибута класса, чтобы вы могли просто удалить их с помощью кнопки сброса (как я заметил, что у вас есть cmds.delete(all=True), который, я думаю, больше не поддерживается в Maya), или сохраните элементы пользовательского интерфейса в self.ui_element. Таким образом, на них можно ссылаться позже как на переменную без возможных конфликтов из-за открытия нескольких окон, в которых есть такие кнопки, как «UI_CreateButton» или «okButton» и т. д.

import maya.cmds as cmds

class UI_Test_thingy():
    windowName = 'UserInterface'
    version = 'v1.1.1'
    debug = True
    createdThingys = []

    def __init__(self):
        self.drawUI()


    def drawUI(self):
        if UI_Test_thingy.debug: print 'DEBUG - drawUI called'
        #check to see if window exists
        try:
            cmds.deleteUI(UI_Test_thingy.windowName)

        except:
            pass

        #create actual window
        UIwindow = cmds.window(UI_Test_thingy.windowName, title = "User Interface Test {}".format(UI_Test_thingy.version), w = 500, h = 700, mnb = False, mxb = False, sizeable = False)
        mainLayout = cmds.columnLayout(w = 300, h =500)
        cmds.button(label = "Reset", w = 300, command=self.SceneClear)

        self.polygonSelectMenu = cmds.optionMenu(w = 250, label = "Polygon Selection:")
        cmds.menuItem(label = " ")
        cmds.menuItem(label = "Sphere")
        cmds.menuItem(label = "Cube")
        cmds.menuItem(label = "Cylinder")
        cmds.menuItem(label = "Cone")

        cmds.button(label = "Create", w = 200, command=self.ObjectCreation)

        cmds.button(label = "Delete", w = 200, command=self.DeleteButton)#Deletes selected object   

        cmds.showWindow(UIwindow) #shows window


    def DeleteButton(self, *args):
        if UI_Test_thingy.debug: print 'DEBUG - DeleteButton called: args: {}'.format(args)
        cmds.delete()


    def SceneClear(self, *args):
        if UI_Test_thingy.debug: print 'DEBUG - SceneClear called: args: {}'.format(args)
        thingsToDel = UI_Test_thingy.createdThingys[:] # copy the list of things created by this script
        UI_Test_thingy.createdThingys = [] # reset the list before deleteing the items
        print 'deleteing: {}'.format(thingsToDel)
        if thingsToDel:
            cmds.delete( thingsToDel ) #Deletes all objects created by this script

    def ObjectCreation(self, *args):
        if UI_Test_thingy.debug: print 'DEBUG - ObjectCreation called: args: {}'.format(args)
        menuVal = cmds.optionMenu(self.polygonSelectMenu, q=True, value=True)
        if menuVal == "Sphere": 
            UI_Test_thingy.createdThingys += cmds.polySphere(name = "Sphere") # store the results to the class attr createdThingys
        elif menuVal == "Cube":
            UI_Test_thingy.createdThingys += cmds.polyCube(name = "Cube") # store the results to the class attr createdThingys
        elif menuVal == "Cylinder":
            UI_Test_thingy.createdThingys += cmds.polyCylinder(name = "Cylinder") # store the results to the class attr createdThingys
        elif menuVal == "Cone":
            UI_Test_thingy.createdThingys += cmds.polyCone(name = "Cone") # store the results to the class attr createdThingys


if __name__ == '__main__':
    ui = UI_Test_thingy()
person mr.matt    schedule 06.03.2015