class OptionMenu(Pmw
.MegaWidget
):
def __init__(self
, parent
= None, **kw
):
# Define the megawidget options.
('initialitem', None, INITOPT
),
('labelmargin', 0, INITOPT
),
('labelpos', None, INITOPT
),
('sticky', 'ew', INITOPT
),
self
.defineoptions(kw
, optiondefs
)
# Initialise the base class (after defining the options).
Pmw
.MegaWidget
.__init
__(self
, parent
)
interior
= self
.interior()
self
._menubutton
= self
.createcomponent('menubutton',
Tkinter
.Menubutton
, (interior
,),
self
._menubutton
.grid(column
= 2, row
= 2, sticky
= self
['sticky'])
self
._menu
= self
.createcomponent('menu',
Tkinter
.Menu
, (self
._menubutton
,),
self
._menubutton
.configure(menu
= self
._menu
)
interior
.grid_columnconfigure(2, weight
= 1)
interior
.grid_rowconfigure(2, weight
= 1)
self
.createlabel(interior
)
# Add the items specified by the initialisation option.
self
.setitems(self
['items'], self
['initialitem'])
# Check keywords and initialise options.
def setitems(self
, items
, index
= None):
# Clean up old items and callback commands.
for oldIndex
in range(len(self
._itemList
)):
tclCommandName
= str(self
._menu
.entrycget(oldIndex
, 'command'))
self
._menu
.deletecommand(tclCommandName
)
self
._menu
.delete(0, 'end')
self
._itemList
= list(items
)
# Set the items in the menu component.
self
._menu
.add_command(label
= item
,
command
= lambda self
= self
, item
= item
: self
._invoke
(item
))
# Set the currently selected value.
var
= str(self
._menubutton
.cget('textvariable'))
# None means do not change text variable.
elif str(self
._menubutton
.cget('text')) in items
:
# Do not change selection if it is still valid
index
= self
.index(index
)
text
= self
._itemList
[index
]
def getcurselection(self
):
var
= str(self
._menubutton
.cget('textvariable'))
return str(self
._menubutton
.cget('text'))
return self
._menu
.tk
.globalgetvar(var
)
return self
.getcurselection()
def setvalue(self
, text
):
var
= str(self
._menubutton
.cget('textvariable'))
self
._menubutton
.configure(text
= text
)
self
._menu
.tk
.globalsetvar(var
, text
)
listLength
= len(self
._itemList
)
if type(index
) == types
.IntType
:
raise ValueError, 'index "%s" is out of range' % index
raise ValueError, 'OptionMenu has no items'
index
= self
.getcurselection()
raise ValueError, 'OptionMenu has no items'
if index
in self
._itemList
:
return self
._itemList
.index(index
)
'bad index "%s": must be a ' \
'name, a number, Pmw.END or Pmw.SELECT' % (index
,)
def invoke(self
, index
= Pmw
.SELECT
):
index
= self
.index(index
)
text
= self
._itemList
[index
]
return self
._invoke
(text
)
command
= self
['command']