[Maya Python] Create a Shelf Button with a Contextual Menu

Submitted by Benoit on Sat, 04/24/2010 - 17:36

To create a shelf button with a contextual menu, we must use the undocumented -menuItem (-mi) flag. If you type help shelfButton in the Maya console, you get something like:

help shelfButton;
// Result:


Synopsis: shelfButton [flags] [String]
Flags:
-e -edit
-q -query
-ais -actionIsSubstitute on|off
...
-mi -menuItem String String (multi-use)
...

The menuItem flags takes a String String (multi-use) as an argument. The first string is the menu's label, the second one is the MEL command to execute. As it is a multi-use, we have to pass a list of list of strings of the form:

[["menulabel1", "melcommand1"], ["menulabel2", "melcommand2"]]

Example:

#=========================================================================
# This script creates a shelf button with a contextual menu
#=========================================================================
 
# Import PyMel 0.9.2
import pymel as pm 
 
# Create ShelfLyout PyNode for TEST Maya shelf
myShelf = pm.ShelfLayout('TEST')
 
# Create a shelfButton with a contextual menu
myShelfButton2 = pm.ShelfButton(parent = myShelf,
                               enable = 1,
                               annotation = "Create spheres",
                               label = "Create spheres",
                               image1 = "sphere.xpm",
                               style = "iconOnly",
                               menuItem = [["Create Small Sphere", 
                                            "polySphere -radius 0.2"], 
                                            ["Create Normal Sphere", 
                                             "polySphere -radius 0.5"], 
                                             ["Create Big Sphere", 
                                              "polySphere -radius 1"]])

Best regards,
Benoît