Adding sub-menus in Python

In Python, use Menu.AddSubMenu to add a submenu.

def SubMenuTest_Menu_Init( in_ctxt ):
	oMenu = in_ctxt.Source
	subMnu = oMenu.AddSubMenu( "Test SubMenu" )
	subMnu.AddCommandItem("Test", "Test")
	return true

Don’t use AddItem, because in Python the derived class methods of the returned object are not resolved properly (it’s an issue with late binding). Basically, with AddItem you end up with a Menu object that supports just the MenuItem interface. So, methods like AddCommandItem, which belong to the derived Menu class, are not resolved and you get errors like this:

# ERROR : Traceback (most recent call last):
#   File "<Script Block 2>", line 55, in Test_Menu_Init
#     subMnu.AddCommandItem("Duplicate Single", "Duplicate Single")
#   File "C:\Program Files\Autodesk\Softimage 2011\Application\python\Lib\site-packages\win32com\client\", line 454, in __getattr__
#     raise AttributeError, "'%s' object has no attribute '%s'" % (repr(self), attr)
# AttributeError: '<win32com.gen_py.Softimage|XSI Object Model Library v1.5.MenuItem instance at 0x517703560>' object has no attribute 'AddCommandItem'

Notice how it says that MenuItem instance has no attribute ‘AddCommandItem’.
AddCommandItem is defined by the derived Menu class.

Before the AddSubMenu method was added, you had to workaround this with win32com.client.Dispatch:

subMnu = win32com.client.Dispatch( oMenu.AddItem("Test SubMenu", constants.siMenuItemSubmenu ) )

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s