def shelf(): """ Add a new shelf in Maya with all the tools that are provided in the SHELF_TOOLS variable. If the tab exists it will be deleted and re-created from scratch. """ # get top shelf gShelfTopLevel = mel.eval("$tmpVar=$gShelfTopLevel") # get top shelf names shelves = cmds.tabLayout(gShelfTopLevel, query=1, ca=1) # delete shelf if it exists if SHELF_NAME in shelves: cmds.deleteUI(SHELF_NAME) # create shelf cmds.shelfLayout(SHELF_NAME, parent=gShelfTopLevel) # add modules for tool in SHELF_TOOLS: if tool.get("image1"): cmds.shelfButton(style="iconOnly", parent=SHELF_NAME, **tool) else: cmds.shelfButton(style="textOnly", parent=SHELF_NAME, **tool)
def shelf(): """ Add a new shelf in Maya with the tools that is provided in the SHELF_TOOL variable. If the tab exists it will be checked to see if the button is already added. If this is the case the previous button will be deleted and a new one will be created in its place. """ # get top shelf gShelfTopLevel = mel.eval("$tmpVar=$gShelfTopLevel") # get top shelf names shelves = cmds.tabLayout(gShelfTopLevel, query=1, ca=1) # create shelf if SHELF_NAME not in shelves: cmds.shelfLayout(SHELF_NAME, parent=gShelfTopLevel) # get existing members names = cmds.shelfLayout(SHELF_NAME, query=True, childArray=True) or [] labels = [cmds.shelfButton(n, query=True, label=True) for n in names] # delete existing button if SHELF_TOOL.get("label") in labels: index = labels.index(SHELF_TOOL.get("label")) cmds.deleteUI(names[index]) # add button cmds.shelfButton(style="iconOnly", parent=SHELF_NAME, **SHELF_TOOL)
def loadShelf(index): """loadShelf convert shelf.mel loadShelf global proc to python code Parameters ---------- index : int the loading shelf index """ varName="shelfName" + str(index) shelfName=str(cmds.optionVar(q=varName)) if cmds.shelfLayout(shelfName, exists=1) and cmds.shelfLayout(shelfName, query=1, numberOfChildren=1) == 0: shelfFileNum="shelfFile" + str(index) shelfFile=cmds.optionVar(q=shelfFileNum) if shelfFile and mel.eval("exists %s"%shelfFile): cmds.setParent(shelfName) shelfVersion = "" try: shelfVersion = mel.eval("eval %s"%shelfFile) except: print "eval %s fail" % shelfFile import traceback traceback.print_exc() return False cmds.optionVar(intValue=(("shelfLoad" + str(index)), True)) if shelfVersion: cmds.optionVar(stringValue=(("shelfVersion" + str(index)), shelfVersion)) if cmds.shelfLayout(shelfName, exists=1): cmds.shelfLayout(shelfName, edit=1, version=shelfVersion) return True
def collectShelfData(): # NOTE 加载所有的工具架 - 默认不加载全部 参考 commandLuancher 插件 loadShelves() # NOTE 获取工具架名称 gShelfTopLevel = mel.eval("$temp = $gShelfTopLevel") shelves = cmds.shelfTabLayout(gShelfTopLevel,query=1,ca=1) labels = cmds.shelfTabLayout(gShelfTopLevel,query=1,tl=1) # NOTE 获取所有的工具架分隔符的信息 for i,[shelf,label] in enumerate(zip(shelves,labels),1): # NOTE 获取完整组件名称 shelf = cmds.shelfLayout(shelf,query=1,fpn=1) if not cmds.shelfLayout(shelf,query=1,ca=1): print "[collapsibleShelf] %s empty child" % shelf continue separator = "" for item in cmds.shelfLayout(shelf,query=1,ca=1): if cmds.separator(item,query=1,ex=1): separator = item if shelf not in shelf_data: shelf_data[shelf] = {} shelf_data[shelf][separator] = [] elif cmds.shelfButton(item,query=1,ex=1): print item,mayaToQT(item) DraggableHandler(mayaToQT(item)) if not separator : continue shelf_data[shelf][separator].append(item)
def shelfLayoutOnly(self): dirfileList = dirListFilePath( self.psePath ) for item in dirfileList: mc.shelfLayout(item, cwh=(188, 196)) self.iconButton( item ) mc.setParent('mainShelfTab') mc.setParent('..')
def InstallShelf(): #---------------------- # Add a shelf #---------------------- shelfName = "TressFX" layout = mel.eval('$tmp=$gShelfTopLevel') if cmds.shelfLayout( shelfName, query=True, exists=True ): # If the shelf exists, delete buttons and delete shelf for buttons in cmds.shelfLayout(shelfName, query=True, childArray=True) or []: cmds.deleteUI(buttons) cmds.setParent(layout + '|' + shelfName) else: # If the shelf doesn't exist, create a new one cmds.setParent(layout) cmds.shelfLayout(shelfName) # create a button cmds.shelfButton( label='Export', command='import TressFX_Exporter\nTressFX_Exporter.UI()', #command='TressFX_Exporter.UI()', sourceType='python', annotation='Launch TressFX exporter', #image='', # This empty icon image will cause a warning message like 'Pixmap file not found, using default.'. style='textOnly')
def animationshelflayout(self): mc.shelfLayout('animationshelf', h=40) mc.shelfButton(annotation='Create IK handle.', image1='kinHandle.png', command="""maya.mel.eval("IKHandleTool();")""") mc.shelfButton(annotation='JointTool.', image1='kinJoint.png', command="""maya.mel.eval("JointTool();")""") mc.shelfButton(annotation='OrientJoint.', image1='orientJoint.png', command="""maya.mel.eval("OrientJointOptions();")""") mc.shelfButton(annotation='SetKey.', image1='setKeyframe.png', command='mc.setKeyframe()') mc.shelfButton(annotation='directionallight.', image1='directionallight.png', command='mc.directionalLight()') mc.shelfButton(annotation='spotLight.', image1='spotlight.png', command='mc.spotLight()') mc.shelfButton(annotation='pointLight.', image1='pointlight.png', command='mc.pointLight()') mc.shelfButton(annotation='CreateCammera.', image1='view.png', command='mc.camera()') mc.setParent('..')
def buildMainLayout(self): '''Build the main part of the ui ''' tabs = mc.tabLayout() tab1 = mc.columnLayout(adj=True) mc.scrollLayout(cr=True) self.shelfLayout = mc.shelfLayout() self.refreshShelfLayout() mc.setParent(tabs) tab2 = mc.columnLayout(adj=True) mc.separator(height=8, style='none') mc.text('Select curve(s) to export. Multiple selected curves will be combined.') mc.text('Center and fit the curve in the viewport,') mc.text('and make sure nothing else is visible for best icon creation.') mc.separator(height=16, style='in') mc.button('Export Selected Curve', command=self.exportControl, annotation='Select a nurbsCurve to export.') mc.tabLayout( tabs, edit=True, tabLabel=((tab1, 'Import'), (tab2, 'Export') )) if not mc.shelfLayout(self.shelfLayout, query=True, numberOfChildren=True): mc.tabLayout( tabs, edit=True, selectTab=tab2)
def Newtab(*args): sel_tab = mc.shelfTabLayout('tabs',q=1,st=1) crnt_tab= mc.shelfTabLayout(sel_tab,q=1,ca=1) Newtab = mc.promptDialog( title='Create New Tab', message='New Tab Name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel') if Newtab == 'OK': n_text = mc.promptDialog(query=True, text=True) if n_text == '': mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is not valid', button=['OK'] ,defaultButton='Yes') else: if crnt_tab: for each in crnt_tab: if each == n_text: mc.confirmDialog (title='Error' ,message= 'Sorry, The name entered is already exists', button=['OK'] ,defaultButton='Yes') return #else: if sel_tab == 'Animation': Nw_tab=savepathini+'Savepose/Animation/'+n_text+'/' mc.shelfLayout(n_text,w=450,h=200,bgc=(0.3,0.3,0.3),p=Animation) mc.sysFile(Nw_tab, makeDir=True ) else: mc.shelfLayout(n_text,w=450,h=200,bgc=(0.3,0.3,0.3),p=Poses) Nw_tab=savepathini+'Savepose/Poses/'+n_text+'/' mc.sysFile(Nw_tab, makeDir=True ) mc.shelfTabLayout(sel_tab,e=1,st=n_text)
def _cleanOldShelf(self): if mc.shelfLayout(self.name, ex=1): if mc.shelfLayout(self.name, q=1, ca=1): for each in mc.shelfLayout(self.name, q=1, ca=1): mc.deleteUI(each) else: mc.shelfLayout(self.name, p="ShelfLayout")
def execute(): """ Add a new shelf in Maya with all the tools that are provided in the SHELF_TOOLS variable. If the tab exists it will be deleted and re-created from scratch. """ shelf_main = mel.eval("$tmpVar=$gShelfTopLevel") shelves = cmds.tabLayout(shelf_main, query=True, childArray=True) if SHELF_NAME not in shelves: cmds.shelfLayout(SHELF_NAME, parent=shelf_main) names = cmds.shelfLayout(SHELF_NAME, query=True, childArray=True) or [] labels = [cmds.shelfButton(n, query=True, label=True) for n in names] if SHELF_TOOL.get("label") in labels: index = labels.index(SHELF_TOOL.get("label")) cmds.deleteUI(names[index]) if SHELF_TOOL.get("image1"): cmds.shelfButton(style="iconOnly", parent=SHELF_NAME, **SHELF_TOOL) else: cmds.shelfButton(style="textOnly", parent=SHELF_NAME, **SHELF_TOOL) log.info("transfer-blend-shape installed successfully.")
def _cleanOldShelf(self): if cmds.shelfLayout(self.name, ex=1): if cmds.shelfLayout(self.name, q=1, ca=1): for each in cmds.shelfLayout(self.name, q=1, ca=1): cmds.deleteUI(each) else: cmds.shelfLayout(self.name, p="ShelfLayout")
def make_flottitools_shelf(): try: flottishelf_fullpath = cmds.shelfLayout(FLOTTI_SHELF_NAME, q=True, fullPathName=True) return flottishelf_fullpath except RuntimeError: flottishelf_shortname = mel.eval( 'addNewShelfTab \"{0}\";'.format(FLOTTI_SHELF_NAME)) flottishelf_fullpath = cmds.shelfLayout(flottishelf_shortname, q=True, fullPathName=True) user_shelf_dir = os.path.abspath(cmds.internalVar(userShelfDir=True)) save_shelf_path = os.path.join(user_shelf_dir, "shelf_{0}".format(FLOTTI_SHELF_NAME)) cmds.saveShelf(flottishelf_fullpath, save_shelf_path) flottitools_dir = os.path.abspath( os.path.dirname(os.path.dirname(__file__))) button_cmd = 'import sys\n' button_cmd += 'if \'{0}\' not in sys.path: sys.path.append(\'{0}\')\n'.format( flottitools_dir) button_cmd += 'import flottitools.ui.averageweights_ui as avgwtsui\n' button_cmd += 'avgwtsui.average_weights()' icon_path = os.path.abspath( os.path.join(os.path.dirname(__file__), 'ui', 'averageweights_icon.png')) cmds.setParent(flottishelf_shortname) avgwts_shelfbutton = cmds.shelfButton(image1=icon_path, sourceType="python", label="Average Weights", annotation="Average Weights", command=button_cmd)
def create_shelf(): """ Create the OBB shelf Raises: None Returns: None """ tab_layout = mel.eval('$pytmp=$gShelfTopLevel') shelf_exists = cmds.shelfLayout('OBB', exists=True) if shelf_exists: cmds.deleteUI('OBB', layout=True) shelf = cmds.shelfLayout('OBB', parent=tab_layout) for button, kwargs in buttons.items(): img = QtGui.QImage(kwargs['image']) kwargs['width'] = img.width() kwargs['height'] = img.height() cmds.shelfButton(label=button, parent=shelf, **kwargs) # Fix object 0 error. shelves = cmds.shelfTabLayout(tab_layout, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=("shelfName%d" % (index + 1), str(shelf)))
def create_shelf(): """ Create the OBB shelf Raises: None Returns: None """ tab_layout = mel.eval('$pytmp=$gShelfTopLevel') shelf_exists = cmds.shelfLayout('OBB', exists=True) if shelf_exists: cmds.deleteUI('OBB', layout=True) shelf = cmds.shelfLayout('OBB', parent=tab_layout) for button, kwargs in buttons.items(): img = QtGui.QImage(kwargs['image']) kwargs['width'] = img.width() kwargs['height'] = img.height() cmds.shelfButton(label=button, parent=shelf, **kwargs) # Fix object 0 error. shelves = cmds.shelfTabLayout(tab_layout, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=("shelfName%d" % (index+1), str(shelf)))
def _updateShelvesInfo(self): """Update shelves info.""" self.exists = cmds.shelfLayout(self.name, exists=True) self.buttons = cmds.shelfLayout( self.name, query=True, childArray=True) if self.exists else [] self.layout = '%s|%s' % (cmds.shelfLayout(self.name, q=True, p=True), self.name) if self.exists else ''
def cleanOldShelf(shelfName): """Checks if the shelf exists and empties it if it does""" if cmds.shelfLayout(shelfName, exists=1): if cmds.shelfLayout(shelfName, query=1, childArray=1): for each in cmds.shelfLayout(shelfName, query=1, childArray=1): cmds.deleteUI(each) cmds.deleteUI(shelfName)
def __init__(self, name): self.name = name self.labelBackground = (0, 0, 0, 0) self.labelColour = (.9, .9, .9) mc.shelfLayout(self.name, p="ShelfLayout") mc.setParent(self.name) self.build()
def install(): """ Add a new shelf in Maya with all the tools that are provided in the TOOLS variable. If a tab already exist new buttons that weren't registered yet will be added to the shelf. """ # get top shelf gShelfTopLevel = mel.eval("$tmpVar=$gShelfTopLevel") # get top shelf names shelves = cmds.tabLayout(gShelfTopLevel, query=1, ca=1) # create shelf if it doesn't exist yet if not SHELF_NAME in shelves: cmds.shelfLayout(SHELF_NAME, parent=gShelfTopLevel) # get existing members existing = cmds.shelfLayout(SHELF_NAME, query=True, childArray=True) or [] existing = [cmds.shelfButton(e, query=True, label=True) for e in existing] # add modules for tool in TOOLS: if tool.get("label") in existing: continue if tool.get("image1"): cmds.shelfButton(style="iconOnly", parent=SHELF_NAME, **tool) else: cmds.shelfButton(style="textOnly", parent=SHELF_NAME, **tool)
def getShelfButton(): """getShelfButton Get Command data from Maya Shelf """ # NOTE 获取工具架名称 gShelfTopLevel = mel.eval("$temp = $gShelfTopLevel") shelves = cmds.shelfTabLayout(gShelfTopLevel, query=1, ca=1) labels = cmds.shelfTabLayout(gShelfTopLevel, query=1, tl=1) for i, [shelf, label] in enumerate(zip(shelves, labels), 1): # NOTE 获取完整组件名称 shelf = cmds.shelfLayout(shelf, query=1, fpn=1) if not cmds.shelfLayout(shelf, query=1, ca=1): print "%s empty child" % shelf continue for btn in cmds.shelfLayout(shelf, query=1, ca=1): if cmds.shelfButton(btn, query=1, ex=1): name = cmds.shelfButton(btn, query=1, label=1) icon = cmds.shelfButton(btn, query=1, i=1) # tooltip = cmds.shelfButton(btn,query=1,ann=1) COMMANDS[name] = dict() COMMANDS[name]["name"] = name COMMANDS[name]["pin"] = False if os.path.exists(icon): COMMANDS[name]["icon"] = utils.QIcon(icon) else: COMMANDS[name]["icon"] = utils.QIcon(":/{0}".format(icon)) COMMANDS[name]["group"] = "Shelf: %s" % label COMMANDS[name]["search"] = "%s%s" % (label, name) COMMANDS[name]["hierarchy"] = "%s > %s" % (label, name) COMMANDS[name]["category"] = "shelf" # COMMANDS[name]["menu"] = menu_list[-1] # NOTE 点击运行的代码 command = cmds.shelfButton(btn, query=1, c=1) command_type = cmds.shelfButton(btn, query=1, c=1, stp=1) if command_type.lower() == "mel": # Note 运行双击的 mel 代码 COMMANDS[name]["cmd"] = partial(mel.eval, command) else: # Note 运行双击的 python 代码 COMMANDS[name]["cmd"] = partial( lambda command: eval( compile(command, '<string>', 'exec')), command) # NOTE 查询双击 shelf 状态 options = cmds.shelfButton(btn, query=1, dcc=1) if options: options_type = cmds.shelfButton(btn, query=1, dcc=1, stp=1) if options_type.lower() == "mel": # Note 运行双击的 mel 代码 COMMANDS[name]["cmdOption"] = partial( mel.eval, options) else: # Note 运行双击的 python 代码 COMMANDS[name]["cmdOption"] = partial( lambda x: eval(compile(x, '<string>', 'exec')), options)
def cleanOldShelf(shelfname): import maya.cmds as cmds if cmds.shelfLayout(shelfname, ex=1): if cmds.shelfLayout(shelfname, q=1, ca=1): for each in cmds.shelfLayout(shelfname, q=1, ca=1): print(each) cmds.deleteUI(each)
def _cleanOldShelf(self): """Checks if the shelf exists and empties it if it does or creates it if it does not.""" if cmds.shelfLayout(self.name, ex=1): if cmds.shelfLayout(self.name, q=1, ca=1): for each in cmds.shelfLayout(self.name, q=1, ca=1): cmds.deleteUI(each) else: cmds.shelfLayout(self.name, p="ShelfLayout")
def updateShelf(self, *args): try: allNewShelfTab = self.loadShelfAll() for item in allNewShelfTab: cmds.shelfLayout( '%s'%item, cwh=(35, 35), p='mainShelfTab' ) newShelf = self.readShelf(item) mm.eval(newShelf) except:pass
def shelfLayoutOnly(self): import maya.cmds as mc dirfileList = dirListFilePath( self.psePath ) for item in dirfileList: mc.shelfLayout(item, cwh=(188, 196), p='mainMeShelfTab') self.iconButton( item ) mc.setParent('mainMeShelfTab') mc.setParent('..')
def _cleanOldShelf(self): '''Checks if the shelf exists and empties it if it does or creates it if it does not.''' if mc.shelfLayout(self.name, ex=1): if mc.shelfLayout(self.name, q=1, ca=1): for each in mc.shelfLayout(self.name, q=1, ca=1): mc.deleteUI(each) else: mc.shelfLayout(self.name, p="ShelfLayout")
def _cleanOldShelf(self): '''Checks if the shelf exists and empties it if it does or creates it if it does not.''' if cmds.shelfLayout(self.name, ex=True): if cmds.shelfLayout(self.name, q=True, childArray=True): for each in cmds.shelfLayout( self.name, q=True, childArray=True): cmds.deleteUI(each) else: cmds.shelfLayout(self.name, p="ShelfLayout")
def __init__(self, layout): if cmds.control("itBtn", exists=True): cmds.deleteUI("itBtn") self.layout = layout cmds.shelfLayout(layout, e=True, backgroundColor=[0.2, 0.2, 0.2], spacing=3) self.button = cmds.iconTextButton("itBtn", style="iconOnly", width=33, image=config.getPath( config.kIcon, "logo.png"), parent=layout) currentMode = cmds.setMenuMode() cmds.popupMenu(parent=self.layout, allowOptionBoxes=True) cmds.menuItem(label=u'模型', radioButton=(currentMode == "modelingMenuSet"), command=lambda *_: cmds.setMenuMode("modelingMenuSet")) cmds.menuItem(label=u'绑定', radioButton=(currentMode == "riggingMenuSet"), command=lambda *_: cmds.setMenuMode("riggingMenuSet")) cmds.menuItem(label=u'动画', radioButton=(currentMode == "animationMenuSet"), command=lambda *_: cmds.setMenuMode("animationMenuSet")) cmds.menuItem(label=u'渲染', radioButton=(currentMode == "renderingMenuSet"), command=lambda *_: cmds.setMenuMode("renderingMenuSet")) cmds.menuItem(label=u'特效', radioButton=(currentMode == "dynamicsMenuSet"), command=lambda *_: cmds.setMenuMode("dynamicsMenuSet")) cmds.menuItem(divider=True) cmds.menuItem(label=u'帮助...', command=main.UI) try: cmds.condition("ProjectChanged", delete=True) except: pass cmds.condition("ProjectChanged", state=True) cmds.scriptJob(event=["MenuModeChanged", self.__build__], parent=self.button) cmds.scriptJob(event=["NewSceneOpened", self.__refreshUI__], parent=self.button) cmds.scriptJob(event=["timeUnitChanged", self.__refreshUI__], parent=self.button) cmds.scriptJob(event=["linearUnitChanged", self.__refreshUI__], parent=self.button) cmds.scriptJob(conditionChange=["ProjectChanged", self.__refreshUI__], parent=self.button) om.MSceneMessage.addCallback(om.MSceneMessage.kBeforeSave, lambda *_: cleanUp('boundingBox')) self.__build__() self.__refreshUI__()
def load(yaml_shelf_file, custom_shelf_name=None): ''' Dynamically create and load the shelf in maya ''' if custom_shelf_name: shelf_name = custom_shelf_name else: shelf_name = yaml_shelf_file.split('/')[-1] shelf_name = shelf_name.split('shelf_')[-1] shelf_name = shelf_name.rsplit('.')[0] # Parse the yaml_shelf with codecs.open(yaml_shelf_file, encoding="utf-8") as f_in: shelf_data = yaml.safe_load(f_in) if not shelf_data: raise RuntimeError( 'Could not get config data from {}.'.format(yaml_shelf)) shelf_items = list() for item in shelf_data: shelf_items.append(item) if len(shelf_items) < 1: raise RuntimeError( 'Not enough shelf item in the config file: {}'.format(yaml_shelf)) # This is a fix for the automatically saved shelf function # It will delete a previously shelf created with the plugin if any exist if cmds.shelfLayout(shelf_name, exists=True): cmds.deleteUI(shelf_name) # Declare the $gShelfTopLevel variable as a python variable # The $gShelfTopLevel mel variable is the Maya default variable for the shelves bar UI shelf_top_level = mel.eval('$temp_mel_var = $gShelfTopLevel;') # Create a new shelfLayout in $gShelfTopLevel custom_shelf = cmds.shelfLayout(shelf_name, parent=shelf_top_level) # Create shelf items for shelf_item in shelf_items: if 'separator' in shelf_item.keys()[0]: shelf_separator_data = _parse_shelf_separator(shelf_item) _build_shelf_separator(shelf_separator_data, custom_shelf) else: shelf_item_data = _parse_shelf_item(shelf_item) _build_shelf_item(shelf_item_data, custom_shelf) # Give a name and save the shelf cmds.tabLayout(shelf_top_level, edit=True, tabLabel=[custom_shelf, shelf_name]) user_shelf_dir = cmds.internalVar(userShelfDir=True) user_shelf_fullname = os.path.join(user_shelf_dir, 'shelf_' + shelf_name) user_shelf_fullname = _sanitize_path(user_shelf_fullname) cmds.saveShelf(custom_shelf, user_shelf_fullname)
def remove_shelf(name): if cmds.shelfLayout(name, ex=1): print("Shelf {0} exists.\n".format(name)) if cmds.shelfLayout(name, ca=1, q=1): for each in cmds.shelfLayout(name, ca=1, q=1): print("Deleting {0}...\n".format(each)) cmds.deleteUI(each) cmds.deleteUI(name) else: print("Shelf {0} does not exist.\n".format(name))
def __init__(self, name="customShelf", iconPath=""): self.name = name self.iconPath = iconPath self.labelBackground = (0, 0, 0, 0) self.labelColour = (0.6, 0.8, 1.0) self._removeOlderVersion() cmds.shelfLayout(self.name, p="ShelfLayout") cmds.setParent(self.name) self.build()
def _removeOlderVersion(self): '''Check if the shelf exists and nuc it if so.''' if cmds.shelfLayout(self.name, ex=1): print("Shelf {0} exists.\n".format(self.name)) if cmds.shelfLayout(self.name, ca=1, q=1): for each in cmds.shelfLayout(self.name, ca=1, q=1): print("Deleting {0}...\n".format(each)) cmds.deleteUI(each) cmds.deleteUI(self.name) else: print("Shelf {0} does not exist yet.\n".format(self.name))
def transformshelflayout(self): mc.shelfLayout('transfromshelf', h=100) mc.shelfButton(annotation='Create a sphere.', image1='sphere.png', command='mc.sphere()') mc.shelfButton(annotation='Create a cube.', image1='cube.png', command='mc.nurbsCube()') mc.shelfButton(annotation='Create a cylinder.', image1='cylinder.png', command='mc.cylinder()') mc.shelfButton(annotation='Create a plane.', image1='plane.png', command='mc.plane()') mc.shelfButton(annotation='Create a polySphere.', image1='polySphere.png', command='mc.polySphere()') mc.shelfButton(annotation='Create a polyCube.', image1='polyCube.png', command='mc.polyCube()') mc.shelfButton(annotation='Create a polyCylinder.', image1='polyCylinder.png', command='mc.polyCylinder()') mc.shelfButton(annotation='Create a polyPlane.', image1='polyPlane.png', command='mc.polyPlane()') mc.shelfButton(annotation='Freeze Transformations.', image1='fluidShape.svg', command='mc.makeIdentity(apply=True)', w=50, h=50) mc.shelfButton( annotation='Center Pivot.', image1='buttonManip.svg', command= """object = mc.ls(sl=True); bbox = mc.exactWorldBoundingBox(object);center = [(bbox[0] + bbox[3])/2, (bbox[1]+bbox[4])/2, (bbox[2] + bbox[5])/2];mc.xform(object, piv=center, ws=True)""", w=50, h=50) mc.shelfButton(annotation='Delete History.', image1='menuIconEdit.png', command='mc.DeleteHistory()', w=50, h=50) mc.shelfButton(annotation='CV Curve Tool.', image1='curveCV.png', command="""maya.mel.eval("CVCurveTool();")""", w=50, h=50) mc.shelfButton(annotation='Create a nurbsCircle.', image1='circle.png', command='mc.circle()', w=50, h=50) mc.setParent('..')
def _initialize_shelf(shelf): """ Create a shelf, deleting the previous one if needed. :param shelf: The name of the shelf """ if cmds.shelfLayout(shelf, exists=1): if cmds.shelfLayout(shelf, query=1, childArray=1): for each in cmds.shelfLayout(shelf, query=1, childArray=1): cmds.deleteUI(each) else: cmds.shelfLayout(shelf, parent="ShelfLayout")
def buildShelf(self): if not cmds.shelfLayout(self.NAME_LABEL, ex=1): shelfTab = 'ShelfLayout' cmds.setParent(shelfTab) cmds.shelfLayout(self.NAME_LABEL) for menu in self.LIST_SHELF: cmds.shelfButton(c=self.wrapIm(menu[0]), l=menu[1], iol=menu[1], i='123d.png') print('buildShelf')
def createMyShelf(): # sample code shelfName = 'My_Shelf' test = cmds.shelfLayout(shelfName, ex=True) if test: # If the shelf already exists, clear the contents and re-add the # buttons. newShelf = shelfName buttons = cmds.shelfLayout(newShelf, query=True, childArray=True) cmds.deleteUI(buttons, control=True) else: newShelf = mel.eval('addNewShelfTab %s' % shelfName) cmds.setParent(newShelf)
def shelf() : ''' Creates a peelMocapTools shelf ''' import maya.cmds as m import maya.mel as mel shelfTabName = "peelMocapTools" if not m.shelfLayout(shelfTabName, exists=True) : shelfTab = mel.eval("addNewShelfTab(\"%s\")" % shelfTabName) topShelf = mel.eval("global string $gShelfTopLevel; string $x = $gShelfTopLevel") try : toolShelf = m.shelfLayout("%s|%s" % (topShelf, shelfTabName), q=True, ca=True) if toolShelf is not None : if len(toolShelf) > 0 : m.deleteUI(toolShelf) except RuntimeError : x = 0 kt = 'import mocapCleanup.keyTools as kt;kt.' mx = 'import mocapCleanup.mocap as mx;mx.' ms = 'import mocapCleanup.markerset as mz;mz.' la = 'import mocapCleanup.labeler as la;la.' ld = 'import mocapCleanup.loader as ld;ld.' ca = 'import mocapCleanup.camera as ca;ca.' buttons = [ [ "Load c3d", mx + "loadc3d()", "mocap_loadc3d.bmp" ], [ "Data", ld + "show()", "mocap_data.bmp" ], [ "Gui", la + "show()", "mocap_gui.bmp" ], [ "Fill", kt + "fill()", "mocap_fill.bmp" ], [ "Split Parts", kt + "splitParts()", "mocap_splitParts.bmp" ], [ "Swap Selected", kt + "swap()", "mocap_swapSelected.bmp" ], [ "Swap All", kt + "swapAll()", "mocap_swapAll.bmp" ], [ "Extract Before", kt + "extractBefore()", "mocap_extractBefore.bmp" ], [ "Extract After", kt + "extractAfter()", "mocap_extractAfter.bmp" ], [ "Extract After Sel", kt + "extractSelected()", "mocap_extractSelected.bmp" ], [ "Set Current", kt + "setCurrent('1')", "mocap_setX.bmp" ], [ "Move to Current", kt + "moveToCurrent('1')", "mocap_moveToX.bmp" ], [ "Move 1 to 2", kt + "moveFirstToSecond()", "mocap_moveFirstToSecond.bmp" ], [ "Key Current to match", kt + "keyCurrentToMatch()", "mocap_keyCurrentToMatch.bmp" ], [ "Go to next gap", kt + "goToNextGap()", "mocap_goToNextGap.bmp" ], [ "Toggle Active", kt + "toggleConnectVis()", "mocap_eye.bmp" ], [ "Camera On", ca + "rigidbodyCam()", "mocap_cam_on.bmp" ], [ "Camera Off", ca + "clear()", "mocap_cam_off.bmp" ], ] # [ "Load web data", "import loader\nx=loader.Loader()\nx.show()", "mocap_c3d.bmp" ], # [ "Import Cameras", "import camera\ncamera.importCameras()\n", "mocap_cam.bmp" ], for i in buttons : m.shelfButton(l=i[0], stp="python", c=i[1], i1=i[2], p=shelfTabName)
def speedWindow(self): if mc.windowPref('facialWin', exists=1): mc.windowPref('facialWin', remove=1) if mc.window('facialWin', exists=1): mc.deleteUI('facialWin') mc.window('facialWin', t='Mudan_FacialPanel', w=960, h=430) mc.shelfTabLayout('mainShelfTab', image='smallTrash.png', imageVisible=1) mc.shelfLayout('Flower', cwh=(188, 196)) self.shelfButtonFlower() mc.setParent('..') mc.shelfLayout('Human', cwh=(188, 196)) self.shelfButtonHuman() mc.setParent('..') mc.showWindow()
def createShelf(): # delete the shelf is already exists if cmds.shelfLayout('dmptools', ex=True): fullname = cmds.shelfLayout('dmptools', fpn=True, q=True) cmds.deleteUI(fullname) # create the shelf shelfParent = cmds.shelfTabLayout('ShelfLayout', fpn=True, q=True) cmds.shelfLayout('dmptools', p=shelfParent) # create shelf buttons for button in BUTTONS: b = addButton(button) # select the last created shelf i = cmds.shelfTabLayout(shelfParent, numberOfChildren=True, q=True) cmds.shelfTabLayout(shelfParent, selectTabIndex=i, e=True)
def getShelfButtonsWithTag( tag ): buttons = [] shelves = cmd.lsUI( cl=True, type='shelfLayout' ) or [] for shelf in shelves: if not cmd.shelfLayout( shelf, ex=True ): continue shelfButtons = cmd.shelfLayout( shelf, q=True, ca=True ) or [] for button in shelfButtons: if cmd.control( button , ex=True ): if control( button, q=True, docTag=True ) == buttonTag: buttons.append( button ) return buttons
def create(): if cmds.shelfLayout(shelf_name, exists=True, q=True): cmds.deleteUI(shelf_name) cmds.setParent(main_shelf_parent) cmds.shelfLayout(shelf_name) populate_shelf(shelf_name, button_list) # fix stupid maya error with shelves generated via python top_level_shelf = mel.eval('string $m = $gShelfTopLevel') shelves = cmds.shelfTabLayout(top_level_shelf, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=('shelfName%d' % (index+1), str(shelf)))
def refreshShelfLayout(self, *args): '''Delete and the shelf buttons and remake them ''' shelfButtons = mc.shelfLayout(self.shelfLayout, query=True, childArray=True) if shelfButtons: for child in shelfButtons: mc.deleteUI(child) mc.setParent(self.shelfLayout) for each in os.listdir(REPOSITORY_PATH): if each.endswith('.ctrl'): name = os.path.splitext(each)[0] icon = None imageFile = os.path.join(REPOSITORY_PATH,name+'.png') if os.path.isfile(imageFile): icon = imageFile filename = os.path.join(REPOSITORY_PATH,each) button = mc.shelfButton(command=partial(importControl, name), image=icon, width=70, height=70, imageOverlayLabel=name.replace('_',' ').replace(' ',' '), annotation=name) menus = mc.shelfButton(button, query=True, popupMenuArray=True) if menus: for menu in menus: mc.deleteUI(menu)
def writeShelf(self, shelf): reload(sys) sys.setdefaultencoding('utf-8') self.allShelfButtons = [] children = cmds.shelfLayout(shelf, q=1, ca=1) #children.pop(0) #numS = len(children) j = 1 for name in children: oldLabel = cmds.shelfButton(name, q=1, l=1) oldImage = cmds.shelfButton(name, q=1, i=1) oldImage1 = cmds.shelfButton(name, q=1, i1=1) #oldCommand = cmds.shelfButton('shelfButton370', q=1, i=1) oldCommand = cmds.shelfButton(name, q=1, command=1) oldsourceType = cmds.shelfButton(name, q=1, sourceType=1) oldsourceOverlayLabel = cmds.shelfButton(name, q=1, imageOverlayLabel=1) #oldLabel.decode('gb2312') newCommand = self.remainCommand(oldCommand) newImage = self.remainImage(oldImage) newImage1 = self.remainImage(oldImage1) shelfName = "shelfButton_%s_%s"%(j, shelf) shelfButtonName = '%s -image "%s" -image1 "%s" -imageOverlayLabel "%s" -command "%s" -sourceType "%s" -p "%s" %s;\n'%('shelfButton', newImage, newImage1, oldsourceOverlayLabel, newCommand, oldsourceType, shelf, shelfName) self.allShelfButtons.append(shelfButtonName) j += 1 print newCommand f = open('%s%s%s'%(self.tempDir, shelf, '.txt'), 'w') for item in self.allShelfButtons: f.write(item.encode('utf-8')) f.close #mm.eval('print "%s";'%tip) self.allShelfButtons = []
def openTool(): window = cmds.window('Copymation Toolset', tb=False, s=False) #cmds.windowPref('Copymation_Toolset', ra=True) shelf = cmds.shelfLayout() button = cmds.shelfButton(annotation='Clone animation', image1='animCopymationClone.png', command='animCopymation.clone()', imageOverlayLabel='clone') cmds.shelfButton(annotation="Open advanced copy tool", image1="redo.png", command="", imageOverlayLabel="copy", overlayLabelColor=(1, 1, .25), overlayLabelBackColor=(.15, .9, .1, .4)) cmds.shelfButton(annotation="Open animation cycler tool", image1="undo.png", command="", imageOverlayLabel="cycler", overlayLabelColor=(1, .25, .25)) cmds.shelfButton(annotation="Close Copymation toolset", image1="close.png", command='maya.utils.executeDeferred("cmds.deleteUI(\'Copymation_Toolset\')")' , imageOverlayLabel="close", overlayLabelColor=(1, .25, .25)) #resize toolset buttonH = cmds.shelfButton(button, q=True, h=True) buttonW = cmds.shelfButton(button, q=True, w=True) cmds.window(window, edit=True, widthHeight=(buttonW*4+10, buttonH+10)) #show UI showUI()
def delete_shelf(shelf_name): ''' Delete maya shelf and update maya shelf optionVars :param shelf_name: string: name of the shelf to be deleted :return: ''' if mayaIsBatch(): return if not cmds.shelfLayout(shelf_name, q=True, ex=True): return shelfs = cmds.optionVar(q='numShelves') curret_shelf = None # Shelf preferences. for i in range(shelfs + 1): if shelf_name == cmds.optionVar(q="shelfName%i" % i): curret_shelf = i break # manage shelve ids for i in range(curret_shelf, shelfs + 1): cmds.optionVar(iv=("shelfLoad%s" % str(i), cmds.optionVar(q="shelfLoad%s" % str(i + 1)))) cmds.optionVar(sv=("shelfName%s" % str(i), cmds.optionVar(q="shelfName%s" % str(i + 1)))) cmds.optionVar(sv=("shelfFile%s" % str(i), cmds.optionVar(q="shelfFile%s" % str(i + 1)))) cmds.optionVar(remove="shelfLoad%s" % shelfs) cmds.optionVar(remove="shelfName%s" % shelfs) cmds.optionVar(remove="shelfFile%s" % shelfs) cmds.optionVar(iv=("numShelves", shelfs - 1)) cmds.deleteUI(shelf_name, layout=True) mel.eval("shelfTabChange") log.info('Shelf deleted: % s' % shelf_name)
def writeShelf(self, *args): tip = u'\u606d\u559c\uff0c\u5df2\u6210\u529f\u4fdd\u5b58\uff0c\u672c\u9762\u677f\u4f1a\u7ee7\u7eed\u597d\u597d\u670d\u52a1\u7684' reload(sys) sys.setdefaultencoding('utf-8') allShelfButtons = [] children = cmds.shelfLayout('Tools', q=1, ca=1) children.pop(0) numS = len(children) j = 1 for name in children: oldLabel = cmds.shelfButton(name, q=1, l=1) oldImage = cmds.shelfButton(name, q=1, i=1) oldImage1 = cmds.shelfButton(name, q=1, i1=1) #oldCommand = cmds.shelfButton('shelfButton370', q=1, i=1) oldCommand = cmds.shelfButton(name, q=1, command=1) oldsourceType = cmds.shelfButton(name, q=1, sourceType=1) oldsourceOverlayLabel = cmds.shelfButton(name, q=1, imageOverlayLabel=1) #oldLabel.decode('gb2312') newCommand = self.remainCommand(oldCommand) newImage = self.remainImage(oldImage) newImage1 = self.remainImage(oldImage1) shelfName = "shelfButton_%s"%j shelfButtonName = '%s -image "%s" -image1 "%s" -imageOverlayLabel "%s" -command "%s" -sourceType "%s" %s;\n'%('shelfButton', newImage, newImage1, oldsourceOverlayLabel, newCommand, oldsourceType, shelfName) allShelfButtons.append(shelfButtonName) j = j + 1 print newCommand f = open('%sTools.txt'%self.tempDir, 'w') for item in allShelfButtons: f.write(item.encode('utf-8')) f.close mm.eval('print "%s";'%tip)
def handPose_fromSelect_toShelf(): _shelfName = 'pose_Hand' if not cmds.shelfLayout( _shelfName, q=True, exists=True): mel.eval('addNewShelfTab "%s";'%_shelfName) _cmd ='\n' _cmd +='import maya.cmds as cmds\n' _cmd +='import sys\n' _cmd +='\n' _cmd +=u'# 파이썬 경로 추가\n' _cmd +='_newPath = \'//alfredstorage/Alfred_asset/Maya_Shared_Environment/scripts_Python/Alfred_AssetTools\'\n' _cmd +='if not _newPath in sys.path:\n' _cmd +=' sys.path.append(_newPath)\n' _cmd +='\n' _cmd +=u'# UI Load\n' _cmd +='import Alfred_AssetTools\n' _cmd +='reload(Alfred_AssetTools)\n' _cmd +=__name__+'.handPose_fromSelect_toShelf()\n' cmds.shelfButton( commandRepeatable = True , image1 = 'pythonFamily.png' , label = 'getHandPose', annotation = 'getHandPose from Selection', sourceType = 'python', command = _cmd , imageOverlayLabel = 'getHandPose', parent = _shelfName, ) _cmd = getData_from_selection() if not _cmd: return _result = cmds.promptDialog( title='name', message='pose name:', button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel' ) if _result != 'OK': print _cmd return _label = cmds.promptDialog(query=True, text=True) cmds.shelfButton( commandRepeatable =True , image1 ='commandButton.png' , label ='handPose_'+_label , annotation ='handPose_'+_label , sourceType ='mel', command = _cmd , imageOverlayLabel =_label, parent =_shelfName, )
def create_shelf(): '''Create the mtoatools shelf''' tab_layout = mel.eval('$pytmp=$gShelfTopLevel') shelf_exists = cmds.shelfLayout('mtoatools', exists=True) if shelf_exists: cmds.deleteUI('mtoatools', layout=True) shelf = cmds.shelfLayout('mtoatools', parent=tab_layout) for button, kwargs in buttons.items(): img = QtGui.QImage(kwargs['image']) kwargs['width'] = img.width() kwargs['height'] = img.height() cmds.shelfButton(label=button, parent=shelf, **kwargs)
def initializePlugin(mobject): """Initialization method for Maya Autodesk plugin system; creates new shelf and registers each command.""" # make sure the plug-in path is actually found by the python interpreter if (not len([p for p in sys.path if re.search('plug-ins', p)])): if (sys.platform == "linux" or sys.platform == "linux2"): sys.path.append([p for p in sys.path if re.search('bin$', p)][0] + '/plug-ins') else: sys.path.append([p for p in sys.path if re.search('bin$', p)][0] + '\\plug-ins') # import all sub-modules from directory 'pk_src' (print to console in case of error) for cmd in kPluginCmdName: try: exec('from pk_src import ' + cmd) except: sys.stderr.write("Could not find module 'pk_src.%s'\n" % cmd) # force reload of modules to avoid having maya to restart every time a class definition changes for cmd in kPluginCmdName: try: reload(sys.modules["pk_src." + cmd]) except: sys.stderr.write("Error reloading " + cmd) # get maya plugin module mplugin = OpenMayaMPx.MFnPlugin(mobject) mplugin.setVersion(pk_version) # get top level shelf to create new shelf layout where each command gets its own button to execute command topShelf = mel.eval('$nul = $gShelfTopLevel') # check if old reference still exists and delete it if (cmds.shelfLayout("ProKlaue", exists = 1)): cmds.deleteUI("ProKlaue", lay = 1) # create new shelf layout proKlaue proKlaue = cmds.shelfLayout("ProKlaue", parent = topShelf) # maya messes up the shelf optionVars shelfName1 --> recreate shelf names shelves = cmds.shelfTabLayout(topShelf, query=True, tabLabelIndex=True) for index, shelf in enumerate(shelves): cmds.optionVar(stringValue=("shelfName%d" % (index+1), str(shelf))) # register commands and add buttons to shelf for cmd in kPluginCmdName: try: mplugin.registerCommand( cmd, eval(cmd + "." + cmd + "Creator"), eval(cmd + "." + cmd + "SyntaxCreator") ) exec(cmd + ".addButton('%s')" %(proKlaue)) except: sys.stderr.write("Failed to register command or to add shelf button: %s\n" % cmd)
def removeShelf(): # sample code shelfName = 'My_Shelf' test = cmds.shelfLayout(shelfName, ex=True) if test: mel.eval('deleteShelfTab %s' % shelfName) gShelfTopLevel = mel.eval('$tmpVar=$gShelfTopLevel') cmds.saveAllShelves(gShelfTopLevel) else: return
def build(self): if cmds.window( 'speedWin', ex=1 ): cmds.deleteUI( 'speedWin' ) if cmds.windowPref( 'speedWin', ex=1 ): cmds.windowPref( 'speedWin', remove=1 ) cmds.window( 'speedWin', t='SpeedTool', wh=(350, 260)) cmds.shelfTabLayout( 'mainShelfTab', image='smallTrash.png', imageVisible=True ) self.shelf = cmds.shelfLayout( 'Tools', cwh=(35, 35) ) cmds.shelfButton('save',imageOverlayLabel="save", i1='menuIconWindow.png', c=self.writeShelf) self.updateShelf() cmds.setParent( '..' ) cmds.setParent( '..' ) cmds.showWindow()
def changeToolTip(self, toolTip, buttonText): ###Change the tooltip from code to user friendly #####WARNING: Method looks at button label, not icon label, which may be different activeShelf = self.currentShelf() buttons = cmds.shelfLayout(activeShelf, query=True, childArray=True) # print dir(buttons[0]) for button in buttons: buttonPath = activeShelf + "|" + button buttonLabel = cmds.shelfButton(buttonPath, query = True, label = True) if buttonLabel == buttonText: cmds.shelfButton(buttonPath, edit = True, annotation = toolTip)
def _removeFromShelf(s, name, code): allShelf = cmds.tabLayout(s.shelf, ca=True, q=True) for s in allShelf: buttons = cmds.shelfLayout(s, q=True, ca=True) if buttons: for b in buttons: label = cmds.shelfButton(b, q=True, l=True) command = cmds.shelfButton(b, q=True, c=True) if label == name and command == code: Say().it("Removing shelf button: %s." % b) cmds.deleteUI(b, ctl=True)
def shelfButtonHuman(self): children = mc.shelfLayout('Human', q=1, ca=1) if children == None: pass else: for name in children: oldLabel = mc.shelfButton(name, q=1, l=1) if oldLabel in self.flowerFacial: mc.deleteUI(name, ctl=1) for item in self.humanFacial: mc.shelfButton('%s_bt'%item, l=item, w=188, h=196, image1='%s/%s.jpg'%(self.iconPath, item), annotation=item, dcc='facialPanel.update(\"' + item + '\")')
def get(cls, name, layout=None): if not layout: layout = cls.top_level_layout() cmds.setParent(layout) shelf = cmds.shelfLayout(name, q=True, exists=True) if shelf: return cls(name, layout) else: raise NameError("Unable to find shelf: " + name)
def createShelf(): iconPath = os.path.abspath(os.path.join(os.path.dirname(CM_Tools.__file__),".."))+"/Icons/" gShelfTopLevel = maya.mel.eval('global string $gShelfTopLevel; $temp = $gShelfTopLevel;') cmShelf = gShelfTopLevel + '|TurboSquid' if cmds.shelfLayout(cmShelf, exists=True): cmds.deleteUI(cmShelf) if not cmds.shelfLayout(cmShelf, exists=True): cmds.setParent(gShelfTopLevel) cmds.shelfLayout('TurboSquid') else: cmds.setParent(cmShelf) if not cmds.shelfButton('CheckMate', exists=True): checkMateButton = cmds.shelfButton('CheckMate', label='CheckMate', parent = 'TurboSquid', annotation='Run the CheckMate tools on the current scene', image1 = iconPath + 'CheckMatePro.png', command='from CM_Tools import SystemFile;reload(SystemFile);SystemFile.SystemClass()' ) print checkMateButton cmds.shelfTabLayout(gShelfTopLevel, e=True, st='TurboSquid') cmds.saveAllShelves(gShelfTopLevel)
def create_shelf(): """ create the dmptools shelf """ # delete the shelf is already exists if cmds.shelfLayout(SHELF_NAME, ex=True): fullname = cmds.shelfLayout('dmptools', fpn=True, q=True) cmds.deleteUI(fullname) # create the shelf shelfParent = cmds.shelfTabLayout('ShelfLayout', fpn=True, q=True) shelf = cmds.shelfLayout(SHELF_NAME, p=shelfParent) # add shelf buttons for item in SHELF_ITEMS: if 'separator' in item['name']: # defaultPrint(__name__+' : creating button '+item['name']+'...') add_separator(item, shelf) else: # defaultPrint(__name__+' : creating button '+item['name']+'...') add_button(item, shelf) # select the last created shelf i = cmds.shelfTabLayout(shelfParent, numberOfChildren=True, q=True) cmds.shelfTabLayout(shelfParent, selectTabIndex=i, e=True) # save the shelf cmds.saveShelf(SHELF_NAME, SHELF_FILE)
def initCollapse(): # need to activate each tab. if you dont you'll get an empty array of buttons if you query them cycleThroughShelves() for shelf in getShelves(): shelfButtons = m.shelfLayout(shelf, query=True, childArray=True, fullPathName=True) if shelfButtons is not None: for btn in shelfButtons: btnCommandString = m.shelfButton(btn, q=True, command=True) match = re.search(r"fx_collapse_shelf_buttons.toggle\(\'(.*)\'\,\s*\'(.*)\'\)", btnCommandString) if match: shelf, group = match.group(1), match.group(2) state = getSavedState(shelf, group) setGroupState(shelf, group, state)
def _addToShelf(s, name, code): active = cmds.tabLayout(s.shelf, st=True, q=True) # Grab active shelf buttons = cmds.shelfLayout(active, q=True, ca=True) # List all buttons in shelf missing = True # Shelf button exists here? if buttons: for b in buttons: label = cmds.shelfButton(b, l=True, q=True) if label == name: cmds.shelfButton(b, e=True, c=code) missing = False Say().it("Updated existing shelf button.") if missing: cmds.shelfButton(label=name, c=code, image="daisyLarge.png", p=active) Say().it("Created shelf button.")