Menus

Release: 16/10/2001

Menus can be attached to windows and submenus can be shared between menus. Both of these features are demonstrated by the menus.py demonstration. The most interesting part of the program is the dynamic menu:

def create_submenu(args):

	# The arguments passed were just three lists
	text = args[0]
	flags = args[1]
	links = args[2]

This function is going to be called before the relevant submenu is opened. The first three items in the arguments list are themselves lists.

	# The last three items are the x and y screen coordinates of the
	# menu location and the menu code.

	# Look up the menu object for alteration
	menu = app.menus[args[-1]]

	# Read the screen position
	x, y = args[-3], args[-2]

The last three items are also important, as we need the submenu name to actually be able to change its items.

	# Write the new menu title
	menu.title = 'Dynamic menu at ('+str(x)+', '+str(y)+')'

We update the title by changing its title attribute.

	# Write the lists to the menu's items list
	menu.items = []

	for i in range(0, len(text)):

		menu.items.append( (text[i], flags[i], links[i], None, None) )

The contents of the three lists are used to create new items, none of which provide functionality through their selection by the user.

	# Return value is currently unimportant
	return 'Done'

In this case the return value is unimportant although, having successfully changed a menu, the function should return a value other than None.

dynamic_submenu = app.Menu( None, None, None, None, 'Dynamic menu', [] )

The menu object for this submenu is created, but with no default menu items since they will be filled in when the submenu opens.

# Make the submenu dynamic by adding a message handler. The arguments
# are passed in a list. In this case we are passing three lists of items.
# Not really a good demonstration of the dynamic nature of the menu, but
# illustrates the argument passing feature.
dynamic_submenu.add_messageaction('MenuWarning', create_submenu,
	[
		['My', 'dynamic', 'menu'],
		['shaded', 'dotted', ''],
		[None, None, 'another']
	] )

In order for the submenu to be dynamic, the MenuWarning event must be claimed by the submenu. The information passed to the create_submenu function in the list given is notably non-dynamic.

app.add_menu(dynamic_submenu, 'dynamic submenu')

Finally, the submenu object is registered with the app module where it can be accessed through the menus dictionary.


David Boddie
david@boddie.org.uk