A Menubutton is a widget that looks like a button, but when pressed it pops up a menu. After the user selects an item, the menu disappears.
Here is code that creates a color selection Menubutton (you can download it from http://thinkpython.com/code/menubutton_demo.py):
g = Gui()g.la('Select a color:')colors = ['red', 'green', 'blue']mb = g.mb(text=colors[0])
mb creates the Menubutton. Initially, the text on the button is the name of the default color. The following loop creates one menu item for each color:
for color in colors:g.mi(mb, text=color, command=Callable(set_color, color))
The first argument of mi is the Menubutton these items are associated with.
The command option is a Callable object, which is something new. So far we have seen functions and bound methods used as callbacks, which works fine if you don’t have to pass any arguments to the function. Otherwise you have to construct a Callable object that contains a function, like set_color, and its arguments, like color.
The Callable object stores a reference to the function and the arguments as attributes. Later, when the user clicks on a menu item, the callback calls the function and passes the stored arguments.
Here is what set_color might look like:
def set_color(color):mb.config(text=color)print color
When the user selects a menu item and set_color is called, it configures the Menubutton to display the newly-selected color. It also print the color; if you try this example, you can confirm that set_color is called when you select an item (and not called when you create the Callable object).
- 瀏覽次數:1490