-
Tkinter > créer des menus
The Menu widget is used to implement toplevel, pulldown, and popup menus.
When to use the Menu Widget
This widget is used to display all kinds of menus used by an application. Since this widget uses native code where possible, you shouldn’t try to fake menus using buttons and other Tkinter widgets.
Patterns
Toplevel menus are displayed just under the title bar of the root or any other toplevel windows (or on Macintosh, along the upper edge of the screen). To create a toplevel menu, create a new Menu instance, and use add methods to add commands and other menu entries to it.
root = Tk() def hello(): print "hello!" # create a toplevel menu menubar = Menu(root) menubar.add_command(label="Hello!", command=hello) menubar.add_command(label="Quit!", command=root.quit) # display the menu root.config(menu=menubar)
Pulldown menus (and other submenus) are created in a similar fashion. The main difference is that they are attached to a parent menu (using add_cascade), instead of a toplevel window.
root = Tk() def hello(): print "hello!" menubar = Menu(root) # create a pulldown menu, and add it to the menu bar filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Open", command=hello) filemenu.add_command(label="Save", command=hello) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="File", menu=filemenu) # create more pulldown menus editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Cut", command=hello) editmenu.add_command(label="Copy", command=hello) editmenu.add_command(label="Paste", command=hello) menubar.add_cascade(label="Edit", menu=editmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", command=hello) menubar.add_cascade(label="Help", menu=helpmenu) # display the menu root.config(menu=menubar)
Finally, a popup menu is created in the same way, but is explicitly displayed, using the post method:
root = Tk() def hello(): print "hello!" # create a popup menu menu = Menu(root, tearoff=0) menu.add_command(label="Undo", command=hello) menu.add_command(label="Redo", command=hello) # create a canvas frame = Frame(root, width=512, height=512) frame.pack() def popup(event): menu.post(event.x_root, event.y_root) # attach popup to canvas frame.bind("<Button-3>", popup)
You can use the postcommand callback to update (or even create) the menu every time it is displayed.
counter = 0 def update(): global counter counter = counter + 1 menu.entryconfig(0, label=str(counter)) root = Tk() menubar = Menu(root) menu = Menu(menubar, tearoff=0, postcommand=update) menu.add_command(label=str(counter)) menu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="Test", menu=menu) root.config(menu=menubar)
Reference
Menu(master=None, **options) A menu pane.
__init__(master=None, **options) Creates a menu widget.
master
Parent widget.
**options
Widget options. See the description of the config method for a list of available options.
activate(index) The activate method.
index
add(type, **options) Add (append) an entry of the given type to the menu.
type
What kind of entry to add. Can be one of “command”, “cascade” (submenu), “checkbutton”, “radiobutton”, or “separator”.
**options
Menu options.
activebackground=
activeforeground=
accelerator=
background=
bitmap=
columnbreak=
command=
font=
foreground=
hidemargin=
image=
indicatoron=
label=
menu=
offvalue=
onvalue=
selectcolor=
selectimage=
state=
underline=
value=
variable=
add_cascade(**options) Adds a submenu. See add for a list of options.
**options
add_checkbutton(**options) Adds a checkbutton. See add for a list of options.
**options
add_command(**options) Adds a command. See add for a list of options.
**options
add_radiobutton(**options) Adds a radiobutton. See add for a list of options.
**options
add_separator(**options) Adds a separator. See add for a list of options.
**options
config(**options) Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values.
**options
Widget options.
activebackground= Default value is ‘SystemHighlight’. (the database name is activeBackground, the class is Foreground)
activeborderwidth= Default value is 0. (activeBorderWidth/BorderWidth)
activeforeground= Default value is ‘SystemHighlightText’. (activeForeground/Background)
background= Default value is ‘SystemMenu’. (background/Background)
bg= Same as background.
borderwidth= Default value is 0. (borderWidth/BorderWidth)
bd= Same as borderwidth.
cursor= Default value is ‘arrow’. (cursor/Cursor)
disabledforeground= Default value is ‘SystemDisabledText’. (disabledForeground/DisabledForeground)
font= Default value is ‘MS Sans Serif 8’. (font/Font)
foreground= Default value is ‘SystemMenuText’. (foreground/Foreground)
fg= Same as foreground.
postcommand= No default value. (postCommand/Command)
relief= Default value is ‘flat’. (relief/Relief)
selectcolor= Default value is ‘SystemMenuText’. (selectColor/Background)
takefocus= Default value is 0. (takeFocus/TakeFocus)
tearoff= Default value is 1. (tearOff/TearOff)
tearoffcommand= No default value. (tearOffCommand/TearOffCommand)
title= No default value. (title/Title)
type= Default value is ‘normal’. (type/Type)
delete(index1, index2=None) Deletes one or more menu entries.
index1
The first entry to delete.
index2
The last entry to delete. If omitted, only one entry is deleted.
entrycget(index, option) The entrycget method.
entryconfig(index, **options) Reconfigures the given menu entry. Only the given options are changed; the rest are left as is. See add for a list of available options.
entryconfigure(index, **options) Same as entryconfig (dead link).
index(index) Converts an index (of any kind) to an integer index.
index
Returns:
An integer index.
insert(index, itemType, **options) Inserts an entry of the given type in the menu. This is similar to add, but inserts an entry
insert_cascade(index, **options) Inserts a submenu.
insert_checkbutton(index, **options) Inserts a checkbutton.
insert_command(index, **options) Inserts a command.
insert_radiobutton(index, **options) Inserts a radiobutton.
insert_separator(index, **options) Inserts a separator. def insert_separator(index, **options)
invoke(index) The invoke method.
post(x, y) Displays the menu at the given position. The position should be given in pixels, relative to the root window.
x Menu position.
y Menu position.
type(index) Gets the type of the given menu entry.
index
Index specifier.
Returns:
Item type.
unpost() Removes a posted menu.
yposition(index) Returns the vertical offset for the given entry. This can be used to position a popup menu so that a given entry is under the mouse when the menu appears.
index
Index specifier.
Returns:
The vertical offset, in screen coordinates.
—
Menubutton Widget
The Menubutton widget displays popup or pulldown menu when activated.
This widget is not documented in this version of this document. If you really need it, check the Tk documentation.
When to use the Menubutton Widget
This widget is used to implement various kinds of menus. In earlier versions of Tkinter, it was used to implement toplevel menus, but this is now done with the Menu widget.
Patterns #
Nothing here.
Reference #
Menubutton(master=None, **options) (class)
A button used to post a menu pane.
master
Parent widget.
**options
Widget options. See the description of the config method for a list of available options.
config(**options)
Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values.
**options
Widget options.
activebackground= Default is system specific. (the database name is activeBackground, the class is Foreground)
activeforeground= Default is system specific. (activeForeground/Background)
anchor= Default is CENTER. (anchor/Anchor)
background= Default is system specific. (background/Background)
bg= Same as background.
bitmap= No default value. (bitmap/Bitmap)
borderwidth= Default is 2. (borderWidth/BorderWidth)
bd= Same as borderwidth.
compound= Default is NONE. (compound/Compound)
cursor= No default value. (cursor/Cursor)
direction= Default is “below”. (direction/Direction)
disabledforeground= Default is system specific. (disabledForeground/DisabledForeground)
font= Default is system specific. (font/Font)
foreground= Default is system specific. (foreground/Foreground)
fg= Same as foreground.
height= Default is 0. (height/Height)
highlightbackground= Default is system specific. (highlightBackground/HighlightBackground)
highlightcolor= Default is system specific. (highlightColor/HighlightColor)
highlightthickness= Default is 0. (highlightThickness/HighlightThickness)
image= No default value. (image/Image)
indicatoron= Default is 0. (indicatorOn/IndicatorOn)
justify= Default is CENTER. (justify/Justify)
menu= No default value. (menu/Menu)
padx= Default is ‘4p’. (padX/Pad)
pady= Default is ‘3p’. (padY/Pad)
relief= Default is FLAT. (relief/Relief)
state= Default is NORMAL. (state/State)
takefocus= Default is 0. (takeFocus/TakeFocus)
text= No default value. (text/Text)
textvariable= No default value. (textVariable/Variable)
underline= Default is -1 (no underline). (underline/Underline)
width= Default is 0. (width/Width)
wraplength= Default is 0. (wrapLength/WrapLength)
—
OptionMenu
OptionMenu is a helper class that creates a popup menu, and a button to display it. The option menu is similar to the combobox widgets commonly used on Windows.
To get the currently selected value from an option menu, you have to pass in a Tkinter variable. See the patterns section for some examples.
Patterns
To create an option menu, call the OptionMenu class constructor, and pass in the variable and a list of options.
from Tkinter import * master = Tk() variable = StringVar(master) variable.set("one") # default value w = OptionMenu(master, variable, "one", "two", "three") w.pack() mainloop()
To get the selected option, use get on the variable:
from Tkinter import * master = Tk() var = StringVar(master) var.set("one") # initial value option = OptionMenu(master, var, "one", "two", "three", "four") option.pack() # # test stuff def ok(): print "value is", var.get() master.quit() button = Button(master, text="OK", command=ok) button.pack() mainloop()
The following example shows how to create an option menu from a list of options:
from Tkinter import * # the constructor syntax is: # OptionMenu(master, variable, *values) OPTIONS = [ "egg", "bunny", "chicken" ] master = Tk() variable = StringVar(master) variable.set(OPTIONS[0]) # default value w = apply(OptionMenu, (master, variable) + tuple(OPTIONS)) w.pack() mainloop()
—