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)
python类menu()的实例源码
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
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)
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 )
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)
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)
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)
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)
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
# --------------------------------------------------------------------------------------
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()
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)