Python maya.cmds 模块,menu() 实例源码

我们从Python开源项目中,提取了以下41个代码示例,用于说明如何使用maya.cmds.menu()

项目:surume    作者:tm8r    | 项目源码 | 文件源码
def initialize_plugin():
    cmds.setParent("MayaWindow")
    cmds.menu("surume", l=u"surume", to=True)
    cmds.menuItem(l=u"Check Layout",
                  c=CheckLayoutWindow.main)
    cmds.menuItem(l=u"Convert Color Code",
                  c=ConvertColorCode.show_ui)
    cmds.setParent("..")
项目:surume    作者:tm8r    | 项目源码 | 文件源码
def _create_ui(self):
        u"""UI???"""
        safe_delete_window(self._WINDOW_NAME)
        win = cmds.window(self._WINDOW_NAME, t="Convert Color Code", mb=True, w=480, h=128)
        cmds.menu(l="Option")
        cmds.menuItem(l="ColorEditor", c=self.get_color_from_editor)
        cmds.columnLayout(adj=True, rs=2)
        self.color_code_field = cmds.textFieldButtonGrp(l="Color code", bl="Convert", bc=self._convert)
        self.decimal_point_field = cmds.intFieldGrp(l="Decimal point", nf=1, v1=2)
        self.result_field = cmds.textFieldGrp(l="Result")

        cmds.setParent("..")

        cmds.columnLayout(adj=True)
        self.color_preview = cmds.text(l="", h=24)
        cmds.setParent("..")
        cmds.showWindow(win)
项目:P4VFX    作者:TomMinor    | 项目源码 | 文件源码
def initializeMenu(self, entries):
        try:
            # gMainWindow = MayaInterop.main_parent_window()
            gMainWindow = maya.mel.eval('$temp1=$gMainWindow')
        except RuntimeError as e:
            print e
            print 'Are you running in Batch Python?'
            gMainWindow = None

        try:
            print 'Initialising menu...'
            self.perforceMenu = cmds.menu("PerforceMenu", parent=gMainWindow, tearOff=True, label='Perforce')
            cmds.setParent(self.perforceMenu, menu=True)
        except RuntimeError as e:
            print 'Maya error while trying to create menu:',
            print e
项目:P4VFX    作者:TomMinor    | 项目源码 | 文件源码
def initializeMenu(self, entries):
        try:
            # gMainWindow = MayaInterop.main_parent_window()
            gMainWindow = maya.mel.eval('$temp1=$gMainWindow')
        except RuntimeError as e:
            print e
            print 'Are you running in Batch Python?'
            gMainWindow = None

        try:
            print 'Initialising menu...'
            self.perforceMenu = cmds.menu("PerforceMenu", parent=gMainWindow, tearOff=True, label='Perforce')
            cmds.setParent(self.perforceMenu, menu=True)
        except RuntimeError as e:
            print 'Maya error while trying to create menu:',
            print e
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def buttonWithPopup(self, label=None, command=None, annotation='', shelfLabel='', shelfIcon='render_useBackground', readUI_toArgs={}):
        '''
        Create a button and attach a popup menu to a control with options to create a shelf button or a hotkey.
        The argCommand should return a kwargs dictionary that can be used as args for the main command.
        '''

        if self.icon:
            shelfIcon = self.icon

        if annotation and not annotation.endswith('.'):
            annotation+='.'

        button = mc.button(label=label, command=command, annotation=annotation+' Or right click for more options.')

        mc.popupMenu()
        self.shelfMenuItem(command=command, annotation=annotation, shelfLabel=shelfLabel, shelfIcon=shelfIcon)
        self.hotkeyMenuItem(command=command, annotation=annotation)
        return button
项目:NinjaRipperMayaImportTools    作者:T-Maxxx    | 项目源码 | 文件源码
def createMenu():
    cmds.setParent(mel.eval("$temp1=$gMainWindow"))

    if cmds.control('NR_ImportMenu', exists=True):
        cmds.deleteUI('NR_ImportMenu', menu=True)

    menu = cmds.menu('NR_ImportMenu', label='Ninja Ripper', tearOff=True)

    cmds.menuItem(
        label='Import RIP v4', c="cmds.showWindow('NR_ImportWindow')"
    )

    cmds.menuItem(
        label="Reload Script", c="reload(NinjaRipperMayaImportTools)"
    )
项目:cmt    作者:chadmv    | 项目源码 | 文件源码
def about():
    """Displays the CMT About dialog."""
    name = 'cmt_about'
    if cmds.window(name, exists=True):
        cmds.deleteUI(name, window=True)
    if cmds.windowPref(name, exists=True):
        cmds.windowPref(name, remove=True)
    window = cmds.window(name, title='About CMT', widthHeight=(600, 500), sizeable=False)
    form = cmds.formLayout(nd=100)
    text = cmds.scrollField(editable=False, wordWrap=True, text=cmt.__doc__.strip())
    button = cmds.button(label='Documentation', command='import cmt.menu; cmt.menu.documentation()')
    margin = 8
    cmds.formLayout(form, e=True,
                    attachForm=(
                        (text, 'top', margin),
                        (text, 'right', margin),
                        (text, 'left', margin),
                        (text, 'bottom', 40),
                        (button, 'right', margin),
                        (button, 'left', margin),
                        (button, 'bottom', margin),
                    ),
                    attachControl=(
                        (button, 'top', 2, text)
                    ))
    cmds.showWindow(window)
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def DeleteMenu():
    # Check for existing control, remove it if we can
    if cmds.control(MENU_DATA['menu'][0], exists=True):
        # Found it, delete it
        cmds.deleteUI(MENU_DATA['menu'][0], menu=True)

# Create the menu
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def CreateMenu():
    # Set the diplay's parent
    cmds.setParent(mel.eval("$temp1=$gMainWindow"))

    # Purge old one
    DeleteMenu()

    # Make new menu
    menu = cmds.menu(MENU_DATA['menu'][0], label=MENU_DATA["menu"][1], tearOff=True)    # Recreate the base
    # Add children
    cmds.menuItem(label="Import <- SEAnim", command=lambda x:ImportSEAnim(), annotation="Imports a SEAnim, resetting the scene first")
    cmds.menuItem(label="Import and Blend <- SEAnim", command=lambda x:ImportMergeSEAnim(), annotation="Imports a SEAnim without resetting the scene (Blending the animations together)")
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Export -> SEAnim", command=lambda x:ExportEntireSceneAnim(), annotation="Exports all joints, or all selected joints to a SEAnim file")
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Clean Namespaces", command=lambda x:NamespaceClean(), annotation="Removes all namespaces from the scene")
    cmds.menuItem(label="Place Notetrack", command=lambda x:PlaceNote(), annotation="Places a notetrack at the current scene time")
    cmds.menuItem(label="Select All Joints", command=lambda x:SelectAllJoints(), annotation="Selects all joints")
    cmds.menuItem(label="Select Keyed Joints", command=lambda x:SelectKeyframes(), annotation="Selects keyed joints, this feature does not work with conversion rigs")
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Reset Scene", command=lambda x:ResetSceneAnim(), annotation="Manually reset the scene to bind position")
    cmds.menuItem(label="Clear Curves", command=lambda x:PurgeAllKeyframes(), annotation="Manually delete all cached keyframe curves in the scene")
    cmds.menuItem(divider=True)
    game_menu = cmds.menuItem(label="Game Specific Tools", subMenu=True)    # Make game specific submenu
    cmds.menuItem(label="Call of Duty", subMenu=True)
    cmds.menuItem(label="Attach Weapon to Rig", command=lambda x:WeaponBinder(), annotation="Attatches the weapon to the viewhands, does not work properly with conversion rigs")
    cmds.setParent(game_menu, menu=True)    # Close out menu (Call of Duty)
    cmds.setParent(menu, menu=True)         # Close out menu (Game tools)
    cmds.menuItem(divider=True)
    cmds.menuItem(label="Reload Plugin", command=lambda x:ReloadMayaPlugin(), annotation="Attempts to reload the plugin")
    cmds.menuItem(label="About", command=lambda x:AboutWindow())

# Reloads a maya plugin
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def initializePlugin(mObject):
    # Register the plugin
    mPlugin = OpenMayaMPx.MFnPlugin(mObject, "DTZxPorter", "1.0", "Any")
    # Try and register the file translators
    try:
        # Register seanim
        mPlugin.registerFileTranslator("SEAnim", None, ProxySEAnimRegister)
    except:
        # Log the error
        print("Failed to register SETools!")
    # If we got here, setup the menu
    CreateMenu()

# Unload the plugin
项目:SETools    作者:dtzxporter    | 项目源码 | 文件源码
def uninitializePlugin(mObject):
    # Get the plugin instance
    mPlugin = OpenMayaMPx.MFnPlugin(mObject)
    # Try and unregister the file translators
    try:
        # Unregister seanim
        mPlugin.deregisterFileTranslator("SEAnim")
    except:
        # Log error
        print("Failed to unload SETools!")
    # If we got here, clean up the menu
    DeleteMenu()
项目:pyblish-starter    作者:pyblish    | 项目源码 | 文件源码
def _install_menu():
    from pyblish_starter.tools import creator, loader

    _uninstall_menu()

    def deferred():
        cmds.menu(self.menu,
                  label="Pyblish Starter",
                  tearOff=True,
                  parent="MayaWindow")
        cmds.menuItem("Show Creator", command=creator.show)
        cmds.menuItem("Show Loader", command=loader.show)

    # Allow time for uninstallation to finish.
    QtCore.QTimer.singleShot(100, deferred)
项目:pyblish-starter    作者:pyblish    | 项目源码 | 文件源码
def _uninstall_menu():
    widgets = dict((w.objectName(), w) for w in QtWidgets.qApp.allWidgets())
    menu = widgets.get(self.menu)

    if menu:
        menu.deleteLater()
        del(menu)
项目:P4VFX    作者:TomMinor    | 项目源码 | 文件源码
def addMenuLabel(self, label):
        try:
            cmds.menuItem(label=label, en=False)
        except RuntimeError as e:
            print 'Maya error while trying to add menu entry:',
            print e
项目:P4VFX    作者:TomMinor    | 项目源码 | 文件源码
def addMenuSubmenu(self, label, icon, entries):
        try:
            cmds.menuItem(subMenu=True, tearOff=False, label=label, image=icon)
        except RuntimeError as e:
            print 'Maya error while trying to create submenu:',
            print e

        self.fillMenu(entries)

        try:
            cmds.setParent('..', menu=True )
        except RuntimeError as e:
            print 'Maya error while trying to change menu parent:',
            print e
项目:P4VFX    作者:TomMinor    | 项目源码 | 文件源码
def addMenuCommand(self, label, icon, command):
        try:
            cmds.menuItem( label=label, image=icon, command=command )
        except RuntimeError as e:
            print 'Maya error while trying to change menu parent:',
            print e
项目:P4VFX    作者:TomMinor    | 项目源码 | 文件源码
def addMenuSubmenu(self, label, icon, entries):
        try:
            cmds.menuItem(subMenu=True, tearOff=False, label=label, image=icon)
        except RuntimeError as e:
            print 'Maya error while trying to create submenu:',
            print e

        self.fillMenu(entries)

        try:
            cmds.setParent('..', menu=True )
        except RuntimeError as e:
            print 'Maya error while trying to change menu parent:',
            print e
项目:P4VFX    作者:TomMinor    | 项目源码 | 文件源码
def addMenuCommand(self, label, icon, command):
        try:
            cmds.menuItem( label=label, image=icon, command=command )
        except RuntimeError as e:
            print 'Maya error while trying to change menu parent:',
            print e
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def menus(self):
        #########  modify for inheritence ###########
        #self.widgets["testMenu"] = cmds.menu(l="test")
        self.widgets["menu"] = cmds.menuBarLayout()
        self.widgets["menuFile"] = cmds.menu(label="file")
        cmds.menuItem(l='reset values', c=self.resetValues)
        cmds.menuItem(l="save values", c=self.saveValues)
        cmds.menuItem(l="load values", c=self.loadValues)
        self.widgets["menuHelp"] = cmds.menu(l="help")
        cmds.menuItem(l="print help", c=self.printHelp)
项目:core    作者:getavalon    | 项目源码 | 文件源码
def install(config):
    """Install Maya-specific functionality of avalon-core.

    This function is called automatically on calling `api.install(maya)`.

    """

    # Inherit globally set name
    self._menu = api.Session["AVALON_LABEL"] + "menu"

    _register_callbacks()
    _register_events()
    _set_project()

    # Check if maya version is compatible else fix it, Maya2018 only
    # Should be run regardless of batch mode
    compat.install()

    if not IS_HEADLESS:
        _install_menu()

    pyblish.register_host("mayabatch")
    pyblish.register_host("mayapy")
    pyblish.register_host("maya")

    config = find_host_config(config)
    if hasattr(config, "install"):
        config.install()
项目:core    作者:getavalon    | 项目源码 | 文件源码
def _uninstall_menu():
    app = QtWidgets.QApplication.instance()
    widgets = dict((w.objectName(), w) for w in app.allWidgets())
    menu = widgets.get(self._menu)

    if menu:
        menu.deleteLater()
        del(menu)
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def currentset_get():  # the menu set that is currently in use
    try:
        return cmds.fileInfo("menuSet", q=1)[0]
    except:
        return None
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def menuset_sel(box_ui, key, m_item, menu, *args):
    state = cmds.menuItem(m_item, q=1, isOptionBox=1)
    if state:  # option box used, edit menu set
        menuset_edit(box_ui, key, menu)
    else:  # changing menu set
        data = data_load()
        channelbox_make(box_ui, data[key])
        menulabel_update(key, menu)
        currentset_set(key)
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def menuset_first_sel(box_ui, menu):  # change current menu set to the first available
    data = data_load()
    key = None
    if data:
        key = data.keys()[0]
        currentset_set(key)
        channelbox_make(box_ui, data[key])
    else:
        channelbox_make(box_ui)

    menulabel_update(key, menu)
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def menulabel_update(key, menu):  # change menu label when changing sets
    data = data_load()
    menu_label = ("Menu Set : " + key)[:34] if data else "Menu Set : None"
    # max character limit before falling off screen is 34
    cmds.menu(menu, e=1, label=menu_label)
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_make(box_ui, _menu="jtChannelBox_Menu_Modelling"):
    data = data_load()
    exists = 0
    if box_ui.box is not None:
        del box_ui.box
    else:
        key = currentset_get()
        _menu = _menu if not key else data[key]
    if box_ui.menu_layout is not None:
        exists = 1

    # find the key pertaining to this menu to set as current
    value = [key for key, value in data.iteritems() if value == _menu][0] if data else "None"
    currentset_set(value)
    # cbox.ChannelBox parameters : (layout to parent channel box to, name of file containing menus to use,
    # what to name the file created to store persistent states, True/False/1/0 whether to save states or not)
    box_ui.box = CBox.ChannelBox(box_ui.layout_cbox, _menu, "jtChannelBox_State_Custom", 1)
    cmds.formLayout(box_ui.layout_cbox, e=1,
                    attachForm=[(box_ui.box.layout, "left", 1), (box_ui.box.layout, "right", 1),
                                (box_ui.box.layout, "bottom", 3), (box_ui.box.layout, "top", 0)])

    if exists:
        cmds.formLayout(box_ui.layout_cbox, e=1,
                        attachForm=[(box_ui.menu_layout, "bottom", 10), (box_ui.menu_layout, "right", 0),
                                    (box_ui.menu_layout, "left", 0)],
                        attachControl=(box_ui.box.layout, "bottom", 10, box_ui.menu_layout))
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_menu_states(box, item_key, *args):
    # -----------------------------------------------------------------------------------#
    # MENU STATES : For enabling or disabling menu items based on conditions
    # This will determine if our menuItem is enabled or not, if you want to add a
    # custom menu item with different conditions for being enabled you can do it
    # here by returning prior to the 'return result' on the final line
    #
    # For this to function the "_hasEnableConditions" must be set to true/1
    # -----------------------------------------------------------------------------------#

    # ---------------- MANUALLY ADDED CONDITIONS ----------------#
    # Put your enabled/disabled state overrides here, example:
    # if item_key == "keyForManualOverride":
    #   return 0 to disable or return 1 to enable
    # -----------------------------------------------------------#
    if item_key == "invertShown":
        return 1 if len(box.filter_attrs) >= 1 or len(box.filter_items) >= 1 else 0

    if item_key == "createFilterSet":
        if len(box.filter_attrs) >= 1 or len(box.filter_items) >= 1:
            return 1
        else:
            return 0

    if item_key == "selectFilterSet":
        if "savedFilters" in box.saved_states and len(box.saved_states["savedFilters"][0]) >= 1:
            return 1
        else:
            return 0

    return channelbox_menu_selected_channels(box)


# ----------------------------------------------------------------------------------- #

# ----------------------------------------------------------------------------------- #
# CUSTOM MENU TYPES : Anything set as a "custom" type in the menu can have it's
# behaviour set here by checking for it's unique key
# ----------------------------------------------------------------------------------- #
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_menu_custom(box, item_key, item_type, label, command, parent, enabled):
    if item_key == "selectFilterSet":
        m_item = cmds.menuItem(l=label, en=enabled, subMenu=1, p=parent)
        for f in box.saved_states["savedFilters"][0]:
            item = cmds.menuItem(l=f, p=m_item)
            item_ob = cmds.menuItem(l=f, ob=1, p=m_item)
            cmds.menuItem(item, e=1, c=sysCmd.rpartial(command, box, item, item_key))
            cmds.menuItem(item_ob, e=1, c=sysCmd.rpartial(command, box, item_ob, item_key))


# ----------------------------------------------------------------------------------- #

# ----------------------------------------------------------------------------------- #
# CUSTOM MENU "Objects" : Use this also as an example for implementing a custom menu
# ----------------------------------------------------------------------------------- #
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_command_objectmenu(box, menu, menu_item, m_item, *args):
    state = cmds.menuItem(menu_item, q=1, isOptionBox=1)
    item = cmds.menuItem(menu_item if not state else m_item, q=1, l=1)

    cmds.select(item, deselect=1)
    cmds.select(item, add=1)

    if state:
        mel.eval("editSelected")
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_menu_object(box, menu, *args):
    cmds.menu(menu, e=1, deleteAllItems=1)

    sel = cmds.ls(os=1)

    if not sel:
        cmds.menuItem(l="Nothing selected", p=menu)
        return

    sel.reverse()
    first = 1

    for i in sel:
        m_item = cmds.menuItem(l=i, p=menu)
        m_item_box = cmds.menuItem(m_item, optionBox=1, p=menu)
        cmds.menuItem(m_item, e=1, c=sysCmd.rpartial(channelbox_command_objectmenu, box, menu, m_item, "select " + i))
        cmds.menuItem(m_item_box, e=1, c=sysCmd.rpartial(channelbox_command_objectmenu, box, menu, m_item_box, m_item,
                                                         "select " + i + " [  ]"))

        if first:
            cmds.menuItem(divider=1, p=menu)
            first = 0


# -----------------------------------------------------------------------------------#

# -----------------------------------------------------------------------------------#
# This is where the menu icons are setup
# You probably don't need to modify this, unless you have your own icons to add
# -----------------------------------------------------------------------------------#
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def appendMayaMenu(self, path):
        '''
        Add tools to the maya menus
        '''
        menuLabel = labelFromPath(path)
        formatLabel = menuLabel.replace(' ','').lower()
        menuItemArray = mc.menu(self.mainMenus[formatLabel], query=True, itemArray=True)

        #if this menu hasn't been built yet, run the post menu command to build it
        #that took a long time to figure out.
        if not menuItemArray:
            if self.verbose:
                print 'pre-building menu: ',menuLabel
            pmc = mc.menu(self.mainMenus[formatLabel], query=True, postMenuCommand=True)
            if pmc:
                mm.eval(pmc)
                menuItemArray = mc.menu(self.mainMenus[formatLabel], query=True, itemArray=True)

        #get all the menu items in the menu
        menuItems = dict()
        for each in menuItemArray:
            eachLabel = mc.menuItem(each, query=True, label=True)
            menuItems[eachLabel] = each

        subItems = [posixpath.join(path,x) for x in os.listdir(path) if (x.endswith('.py') or x.endswith('.mel')) and x != '__init__.py']

        if subItems:
            for path in subItems:
                tool = Tool(path)
                self.classifyTool(tool)
                if not tool.errors:
                    tool.createMenuItem(parent=self.mainMenus[formatLabel], labelPrefix=MENU_ITEM_PREFIX+' ', italicized=True)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def dragShiftMiddle(self,*args):
        '''Placeholder for potential commands. This is meant to be overridden by a child class.'''
        pass

    #no drag right, because that is monopolized by the right click menu
    #no alt drag, because that is used for the camera
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def __init__(self, name, title, width=400, height=200, info='', menu=True, module=None):

        self.name = name
        self.title = title
        self.width = width
        self.height = height
        self.info = info
        self.menu = menu

        self.module = module
        if not module or module == '__main__':
            self.module = self.name

        #look for icon
        self.icon = getIcon(name)
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def createMenu(self, *args):
        '''
        Create the main menu for the UI
        '''

        #generate shelf label by removing ml_
        shelfLabel = self.name.replace('ml_','')
        module = self.module
        if not module:
            module = self.name

        #if icon exists, use that
        argString = ''
        if not self.icon:
            argString = ', label="'+shelfLabel+'"'

        mc.menu(label='Tools')
        mc.menuItem(label='Add to shelf', 
                    command='import ml_utilities;ml_utilities.createShelfButton("import '+module+';'+module+'.ui()", name="'+self.name+'", description="Open the UI for '+self.name+'."'+argString+')')
        if not self.icon:
            mc.menuItem(label='Get Icon',
                        command=(_showHelpCommand(websiteURL+'/wp-content/files/'+self.name+'.png')))
        mc.menuItem(label='Get More Tools!', 
                    command=(_showHelpCommand(websiteURL+'/downloads')))
        mc.setParent( '..', menu=True )

        mc.menu(label='Help')
        mc.menuItem(label='About', command=self.about)
        mc.menuItem(label='Documentation', command=(_showHelpCommand(wikiURL+'#'+self.name)))
        mc.menuItem(label='Python Command Documentation', command=(_showHelpCommand(wikiURL+'#\%5B\%5B'+self.name+'\%20Python\%20Documentation\%5D\%5D')))
        mc.menuItem(label='Submit a Bug or Request', command=(_showHelpCommand(websiteURL+'/contact/')))

        mc.setParent( '..', menu=True )
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def shelfMenuItem(self, command=None, annotation='', shelfLabel='', shelfIcon='menuIconConstraints', menuLabel='Create Shelf Button'):
        '''
        This creates a menuItem that can be attached to a control to create a shelf menu with the given command
        '''
        pythonCommand = 'import '+self.name+';'+self.name+'.'+command.__name__+'()'

        mc.menuItem(label=menuLabel,
                    command='import ml_utilities;ml_utilities.createShelfButton(\"'+pythonCommand+'\", \"'+shelfLabel+'\", \"'+self.name+'\", description=\"'+annotation+'\", image=\"'+shelfIcon+'\")',
                    enableCommandRepeat=True,
                    image=shelfIcon)
项目:pyshell    作者:oglops    | 项目源码 | 文件源码
def add_menu(location='Window->General Editors', label='xxx', command='print "xxx"'):
    '''
    Add menu to specified location in main menu.

    Args:
        location: Window->General Editors.
        label: the label on the menu.
        command: the command
    '''
    # gMainWindowMenu='mainWindowMenu'
    import maya.cmds as mc
    menu_path = location.split('->')

    def get_menu_item(label, parent_menu=None):
        'returns menu item with label in parent_menu'
        menu_item = None

        # if it is top level menu
        for m in mc.lsUI(type='menu'):
            if mc.objectTypeUI(m) != 'commandMenuItem' and mc.menu(m, q=1, l=1) == label:
                menu_item = m

                if parent_menu:
                    if not menu_item in mc.menu(parent_menu, q=1, ia=1) or []:
                        continue
                else:
                    break

        pmc = mc.menu(menu_item, q=1, pmc=1)
        if pmc:
            mm.eval(pmc)

        return menu_item

    parent_menu = None
    for m in menu_path:
        menu_item = get_menu_item(m, parent_menu)
        parent_menu = menu_item

    print parent_menu

    # delete existing menuItem
    if mc.menu(parent_menu, q=1, ia=1):
        for m in mc.menu(parent_menu, q=1, ia=1):
            if mc.menuItem(m, q=1, l=1) == label:
                mc.deleteUI(m)
                break

    mc.setParent(menu_item, m=1)
    mc.menuItem(l=label, c=command)
项目:zTools    作者:zethwillie    | 项目源码 | 文件源码
def appendUI():
    """UI for appendPath script"""

    #create window with 3 text fields, buttons call up proc to add path
    if cmds.window("appendPath", exists=True):
        cmds.deleteUI("appendPath")

    widgets["win"] = cmds.window("appendPath", t="zbw_appendPath", w=500, h=5, s=False, rtf=True)

    #create some menus for saving and loading
    cmds.setParent(widgets["win"])
    widgets["menu"] = cmds.menuBarLayout()
    widgets["menuFile"] = cmds.menu(label="file")
    cmds.menuItem(l='Clear Values', c=clearValues)
    cmds.menuItem(l="Save Add Paths", c=saveValues)
    cmds.menuItem(l="Load Add Paths", c=loadValues)

    widgets["tabLO"] = cmds.tabLayout(h=190)
    widgets["columnLO"] = cmds.columnLayout("Add Paths", w=500)
    widgets["path1"] = cmds.textFieldButtonGrp(l="path1", cal=[(1, "left"), (2,"left"),(3,"left")], cw3=(40, 410, 50), bl="<<<", bc=partial(addToField, 1))
    widgets["path2"] = cmds.textFieldButtonGrp(l="path2", cal=[(1, "left"), (2,"left"),(3,"left")], cw3=(40, 410, 50), bl="<<<", bc=partial(addToField, 2))
    widgets["path3"] = cmds.textFieldButtonGrp(l="path3", cal=[(1, "left"), (2,"left"),(3,"left")], cw3=(40, 410, 50), bl="<<<", bc=partial(addToField, 3))

    cmds.separator(h=10, st="single")

    widgets["buttonRCL"] = cmds.rowColumnLayout(nc=3, w=500, cw=[(1,123),(2,247 ),(3,123)])
    widgets["addCloseBut"] = cmds.button(l="Add and Close", w=120, h=30, bgc=(.6, .8, .6), c=applyClose)
    widgets["addBut"] = cmds.button(l="Add Paths!", w=245, h=30, bgc=(.8, .8, .6), c=apply)
    widgets["closeBut"] = cmds.button(l="Close", w=120, h=30, bgc=(.8,.6,.6), c=close)

    cmds.setParent(widgets["columnLO"])
    cmds.separator(h=5, style="single")

    cmds.text("Click the '<<<' buttons to browse for paths to add. Click the 'Add' button to add those \npaths to the 'sys.path' list. Use the 'ViewPath' tab to view current list of paths.", al="center")
    cmds.text("Use 'file->save' to save the selected paths. Use 'file->load' to load previously saved paths")

    #back to window
    cmds.setParent(widgets["tabLO"])
    widgets["columnLO2"] = cmds.columnLayout("View Paths", w=500)
    cmds.text("Double-click to display full path in script editor")
    widgets["listTSL"] = cmds.textScrollList(w=500, h=100, fn="smallPlainLabelFont", append=["click button below", "to refresh this list!"], dcc=printMe)
    refresh()
    cmds.separator(h=5, style="single")

    widgets["columnLO3"] = cmds.columnLayout(w=500)
    widgets["refreshBut"] = cmds.button(l="Refresh Paths", w=500, h=20, bgc=(.5, .5, .6), c=refresh)

    cmds.rowColumnLayout(nc=3, cw=[(1,200),(2,150 ),(3,150)])
    widgets["removeBut"] = cmds.button(l="Remove Selected", w=180,  h=20, bgc=(.7, .5, .5), c=removePath)
    widgets["topBut"] = cmds.button(l="Selected To Top", w=130, h=20, bgc=(.7, .5, .5), c=topPath)
    widgets["bottomBut"] = cmds.button(l="Selected To Bottom", w=130, h=20, bgc=(.7, .5, .5), c=bottomPath)

    #load (and check) previous saves


    cmds.showWindow(widgets["win"])
    cmds.window(widgets["win"], e=True, w=5, h=5, rtf=True)
项目:core    作者:getavalon    | 项目源码 | 文件源码
def _install_menu():
    from ..tools import (
        creator,
        loader,
        publish,
        cbloader,
        cbsceneinventory
    )

    from . import interactive

    _uninstall_menu()

    def deferred():
        cmds.menu(self._menu,
                  label=api.Session["AVALON_LABEL"],
                  tearOff=True,
                  parent="MayaWindow")

        cmds.menuItem("Create...",
                      command=lambda *args: creator.show(parent=self._parent))

        if api.Session.get("AVALON_EARLY_ADOPTER"):
            cmds.menuItem("Load...",
                          command=lambda *args:
                          cbloader.show(parent=self._parent,
                                        use_context=True))
        else:
            cmds.menuItem("Load...",
                          command=lambda *args:
                          loader.show(parent=self._parent))

        cmds.menuItem("Publish...",
                      command=lambda *args: publish.show(parent=self._parent),
                      image=publish.ICON)

        cmds.menuItem("Manage...",
                      command=lambda *args: cbsceneinventory.show(
                          parent=self._parent))

        cmds.menuItem(divider=True)

        cmds.menuItem("System",
                      label="System",
                      tearOff=True,
                      subMenu=True,
                      parent=self._menu)

        cmds.menuItem("Reload Pipeline", command=reload_pipeline)

        cmds.setParent("..", menu=True)

        cmds.menuItem("Reset Frame Range",
                      command=interactive.reset_frame_range)
        cmds.menuItem("Reset Resolution",
                      command=interactive.reset_resolution)

    # Allow time for uninstallation to finish.
    QtCore.QTimer.singleShot(100, deferred)
项目:ModularChannelBox    作者:Vaei    | 项目源码 | 文件源码
def channelbox_symbols(box, *args):
    # create buttons for each menu icon
    b_manip = cmds.symbolButton(p=box.symbol_layout)
    b_speed = cmds.symbolButton(p=box.symbol_layout)
    b_hyper = cmds.symbolButton(p=box.symbol_layout)
    # attach buttons to form layout
    cmds.formLayout(box.symbol_layout, e=1, attachForm=[
        (b_manip, "top", 0),
        (b_manip, "bottom", 1),
        (b_speed, "top", 0),
        (b_speed, "bottom", 1),
        (b_hyper, "top", 0),
        (b_hyper, "bottom", 1),
        (b_hyper, "right", 2),

    ],
                    attachNone=[
                        (b_manip, "left"),
                        (b_speed, "left"),
                        (b_hyper, "left")
                    ],
                    attachControl=[
                        (b_manip, "right", 2, b_speed),
                        (b_speed, "right", 2, b_hyper)

                    ])

    # add the commands for each button (stored in box.sym)
    cmds.symbolButton(b_manip, e=1, c=sysCmd.rpartial(box.sym["pressed"], box, "manipsState"))
    cmds.symbolButton(b_speed, e=1, c=sysCmd.rpartial(box.sym["pressed"], box, "speedState"))
    cmds.symbolButton(b_hyper, e=1, c=sysCmd.rpartial(box.sym["pressed"], box, "hyperbolic"))

    # store the buttons themselves for updating when changed via menu options instead of button presses
    box.symbols["manipsState"] = b_manip
    box.symbols["speedState"] = b_speed
    box.symbols["hyperbolic"] = b_hyper

    # call their update function on creation to set them to their current states (because data is serialized,
    # may not be default on creation)
    for key in box.symbols:
        box.sym["update"](box, key)


# -----------------------------------------------------------------------------------

# ----------------------------------------
# -- MODIFY BELOW THIS LINE AT OWN RISK --
#       You will break many things
# ----------------------------------------

# --------------------------------------------------------------------------------------
# CORE SYSTEM : This is setup very specifically to NOT require you to modify this part
#
# If you need changes here, feel free to email me at the address provided if you feel
# that they could benefit everyone
# --------------------------------------------------------------------------------------
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def createMainMenus(self):

        #mayas main window menu:
        gMainWindow = mm.eval('$temp=$gMainWindow')
        #get all the menus that are children of the main menu
        mainWindowMenus = mc.window(gMainWindow, query=True, menuArray=True)
        #get the label for each of the menus
        #this will be matched against tool directories
        self.mainMenus = dict()
        for name in mainWindowMenus:
            label = mc.menu(name, query=True, label=True)
            #we need to make the label all lower case and no spaces, so we can match properly.
            formatLabel = label.replace(' ','').lower()
            self.mainMenus[formatLabel] = name

        mayaMenuDirectories = list()
        customMenuDirectories = list()

        for folder in os.listdir(self.menusPath):
            if folder.startswith('.'):
                continue

            toolDirectory = posixpath.join(self.menusPath,folder)

            #only directories for this first level
            if not os.path.isdir(toolDirectory):
                if not folder.startswith('__init__') and self.verbose:
                    print 'Root level file being ignored, move this to a sub-directory: ',toolDirectory
                continue

            menuLabel = labelFromPath(toolDirectory)
            formatLabel = menuLabel.replace(' ','').lower()

            if formatLabel in self.mainMenus and not self.mainMenus[formatLabel].startswith(MAIN_MENU_NAME_PREFIX):
                #maya menus
                mayaMenuDirectories.append(toolDirectory)
            else:
                #custom menu
                customMenuDirectories.append(toolDirectory)

        if mayaMenuDirectories:
            for d in mayaMenuDirectories:
                self.appendMayaMenu(d)

        if customMenuDirectories:
            for d in customMenuDirectories:
                self.createCustomMenu(d, parent=gMainWindow, mainMenu=True)

        self.setHotkeys()
项目:ml_tools    作者:morganloomis    | 项目源码 | 文件源码
def createMenuItem(self, parent=None, labelPrefix='', italicized=False):

        if self.isPython:
            menuName = 'mlMenu_'+self.module.__name__.replace('.','_')
        else:
            menuName = 'mlMenu_'+self.name

        #Create the label and print the tool
        label = labelPrefix+self.label

        #keyword args for the menu command
        kwargs = {'italicized':italicized}

        if self.hotkey:
            if len(self.hotkey.keys) == 1:
                kwargs['altModifier'] = self.hotkey.altModifier[0]
                kwargs['ctrlModifier'] = self.hotkey.ctrlModifier[0]

                if self.hotkey.keys[0].isupper():
                    kwargs['shiftModifier'] = True
                kwargs['keyEquivalent'] = self.hotkey.keys[0]

        if self.verbose:
            print self.depth*'\t'+label

        if mc.menuItem(menuName, exists=True):
            mc.deleteUI(menuName)

        insertAfter = None
        if self.isPython and hasattr(self.module,'insertAfter'):
            menuItemArray = mc.menu(parent, query=True, itemArray=True)
            if menuItemArray:
                menuItems = dict()
                for each in menuItemArray:
                    eachLabel = mc.menuItem(each, query=True, label=True)
                    menuItems[eachLabel] = each

                if self.module.insertAfter in menuItems:
                    kwargs['insertAfter'] = menuItems[self.module.insertAfter]

        mc.setParent(parent, menu=True)

        menuName = mc.menuItem(menuName, label=label, command=self.command, **kwargs)