-
Tkinter > les listes, les cases à cocher et les radios
CASES A COCHER (CHECKBUTTON)
Peuvent contenir du texte ou de l’image.
Lorsque’on click sur le bouton, Tkinter appelle une fonction ou une méthode.
The button can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut. By default, the Tab key can be used to move to a button widget.
Each Checkbutton widget should be associated with a variable.
(Also see the Button patterns). To use a Checkbutton, you must create a Tkinter variable. To inspect the button state, query the variable.
import tkinter as tk w = tk.Tk() var = IntVar() c = tk.Checkbutton(w, text="Expand", variable=var).pack() mainloop()
By default, the variable is set to 1 if the button is selected, and 0 otherwise. You can change these values using the onvalue and offvalue options. The variable doesn’t have to be an integer variable:
var = StringVar() c = Checkbutton( master, text="Color image", variable=var, onvalue="RGB", offvalue="L" )
If you need to keep track of both the variable and the widget, you can simplify your code somewhat by attaching the variable to the widget reference object.
v = IntVar() c = Checkbutton(master, text="Don't show this again", variable=v) c.var = v
If your Tkinter code is already placed in a class (as it should be), it is probably cleaner to store the variable in an attribute, and use a bound method as callback:
def __init__(self, master): self.var = IntVar() c = Checkbutton( master, text="Enable Tab", variable=self.var, command=self.cb) c.pack() def cb(self, event): print "variable is", self.var.get()
Reference
Checkbutton(master=None, **options) A toggle button.
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= The background color to use when the button is activated. Default value is system specific. (the database name is activeBackground, the class is Foreground)
activeforeground= The foreground color to use when the button is activated. Default value is system specific. (activeForeground/Background)
anchor= Controls where in the button the text (or image) should be located. Use one of N, NE, E, SE, S, SW, W, NW, or CENTER. Default is CENTER. If you change this, it is probably a good idea to add some padding as well, using the padx and/or pady options. (anchor/Anchor)
background= The button background color. The default is system specific. (background/Background)
bg= Same as background.
bitmap= The bitmap to display in the widget. If the image option is given, this option is ignored. You can either use a built-in bitmap, or load a bitmap from an XBM file. To load the bitmap from file, just prefix the filename with an at-sign (for example “@sample.xbm”). (bitmap/Bitmap)
borderwidth= The width of the button border. The default is system specific, but is usually one or two pixels. (borderWidth/BorderWidth)
bd= Same as borderwidth.
command= A function or method that is called when the button is pressed. The callback can be a function, bound method, or any other callable Python object. No default. (command/Command)
compound= Default is NONE. (compound/Compound)
cursor= The cursor to show when the mouse pointer is moved over the button. (cursor/Cursor)
disabledforeground= The color to use when the button is disabled. The background is shown in the background color. (disabledForeground/DisabledForeground)
font= The font to use in the button. The button can only contain text in a single font. The default is system specific. (font/Font)
foreground= The button foreground color. The default is system specific. (foreground/Foreground)
fg= Same as foreground.
height= The size of the button. If the button displays text, the size is given in text units. If the button displays an image, the size is given in pixels (or screen units). If the size is omitted, it is calculated based on the button contents. (height/Height)
highlightbackground= Default value is system specific. (highlightBackground/HighlightBackground)
highlightcolor= Default value is system specific. (highlightColor/HighlightColor)
highlightthickness=Default value is 1. (highlightThickness/HighlightThickness)
image= The image to display in the widget. If specified, this takes precedence over the text and bitmap options. No default. (image/Image)
indicatoron= Controls if the indicator should be drawn or not. This is on by default.
Setting this option to false means that the relief will be used as the indicator. If the button is selected, it is drawn as SUNKEN instead of RAISED. (indicatorOn/IndicatorOn)justify= Defines how to align multiple lines of text. Use LEFT, RIGHT, or CENTER (default). (justify/Justify)
offrelief= Default is raised. (offRelief/OffRelief)
offvalue= The value corresponding to a non-checked button. The default is 0. (offValue/Value)
onvalue= The value corresponding to a checked button. The default is 1. (onValue/Value)
overrelief= No default value. (overRelief/OverRelief)
padx= Button padding. Default value is 1. (padX/Pad)
pady= Button padding. Default value is 1. (padY/Pad)
relief= Border decoration. This is usually FLAT for checkbuttons, unless they use the border as indicator (via the indicatoron option). (relief/Relief)
selectcolor= Color to use for the selector. Default value is system specific. (selectColor/Background)
selectimage= Graphic image to use for the selector. No default. (selectImage/SelectImage)
state= Button state. One of NORMAL, ACTIVE or DISABLED. Default is NORMAL. (state/State)
takefocus= Indicates that the user can use the Tab key to move to this button. Default is an empty string, which means that the button accepts focus only if it has any keyboard bindings (default is on, in other words). (takeFocus/TakeFocus)
text= The text to display in the button. The text can contain newlines. If the bitmap or image options are used, this option is ignored. (text/Text)
textvariable= Associates a Tkinter variable (usually a StringVar) with the button. If the variable is changed, the button text is updated.
Also see the variable option. (textVariable/Variable)underline= Which character to underline, if any. Default value is -1 (no underline). (underline/Underline)
variable= Associates a Tkinter variable to the button. When the button is pressed, the variable is toggled between offvalue and onvalue. Explicit changes to the variable are automatically reflected by the buttons. (variable/Variable)
width= The size of the button. See height for details. (width/Width)
wraplength= Determines when a button’s text should be wrapped into multiple lines. This is given in screen units. Default is no wrapping. (wrapLength/WrapLength)
deselect() Deselects the checkbox; that is, sets the value to offvalue.
flash() Redraws the button several times, alternating between active and normal appearance.
invoke() Calls the command associated with the button.
select() Selects the button; that is, sets the value to onvalue.
toggle() Toggles the button.
—
LISTBOX (FR)
Permet de sélectionner une ou plusieurs lignes dans la liste.
Listbox(parent, options)
Ce constructeur retourne la nouvelle liste de sélection créée. Ses options incluent:
activestyle=apparence de la ligne active (underline (défaut) - dotbox - none).bgcouleur de fond de la liste de sélection.bdLargeur de la bordure de la liste. 2px par défaut. Pour les valeurs possibles, voir Les dimensions.cursorpointeur de la souris.disabledforeground– La couleur du texte lorsque l’état du widget est ‘disabled’.exportselectionPar défaut, l’utilisateur peut sélectionner le texte à la souris qui est alors copier dans le presse-papier. Pour désactiver, mettre 0.fontpolice de caractère utilisée pour le texte de la liste de sélection. Voir Les polices de caractères.fgcouleur utilisée pour le texte. Voir Les couleurs.heightNombre de lignes montrées dans la liste de sélection. 10 par défaut.highlightbackgroundCouleur de la ligne de focus lorsque le widget ne l’a pas. Voir Focus: réception des saisies clavier.highlightcolorCouleur de la ligne de focus lorsque le widget l’obtient.highlightthicknessÉpaisseur de la ligne de focus.listvariableUne StringVar qui est associée à la liste de sélection dans son ensemble (Voir Variables de contrôle: Les valeurs sous les widgets). L’appel de la méthode get() de cette variable de contrôle retourne une chaîne de la forme "(‘t0′, ‘t1′, …)" où chaque ti est le contenu d’une ligne de la boîte de sélection. Pour modifier toutes les lignes de la boîte, appelez la méthode set(s) sur la variable de contrôle, où s est une chaîne qui contient les valeurs de chaque ligne séparées avec des espaces. Par exemple, si listCon est une StringVar associé à l’option listvariable d’une boîte de sélection, l’appel listCon.set(‘un deux trois’) remplira la boîte avec trois lignes et l’appel listCon.get() retournera "(‘un’, ‘deux’, ‘trois’)".reliefSert à régler le relief de la bordure. ‘sunken’ par défaut. Pour d’autres valeurs, voir Les styles de relief.selectbackgroundLa couleur de fond utilisée pour les lignes sélectionnées.selectborderwidthL’épaisseur de la bordure des lignes de texte sélectionnées. 0 par défaut. Elle est utilisée pour produire un effet de relief ‘raised’ plus ou moins fort autour du texte sélectionné (Voir Les styles de relief).selectforegroundLa couleur du texte sélectionné.selectmodeDétermine le nombre d’items qu’il est possible de sélectionner et la gestion du cliquer-glisser sur la sélection. ‘browse’ - Valeur par défaut, le cliquer-glisser modifie la sélection. ‘single’ - Une seule ligne peut être sélectionnée et il n’est pas possible de déplacer la sélection par cliquer-glisser. ‘multiple’ - Vous pouvez sélectionner plusieurs lignes à la fois. Le fait de cliquer sur une ligne déjà sélectionnée la déselectionne et vice versa. ‘extended’ - vous pouvez sélectionner des lignes adjacentes par cliquer-glisser.statePar défaut, une liste de sélection est dans l’état ‘normal’. Pour désactiver la liste relativement à la souris, mettre la valeur ‘disabled’.takefocusMettre 0 pour sortir ce widget de la liste de «traversée du focus». Voir Focus: réception des saisies clavier.widthLargeur du widget mesurée en caractères (non en pixels). La largeur effective est basée sur la largeur moyenne des caractères de la fonte utilisée. 20 par défaut.xscrollcommandPour faire défiler la liste horizontalement, on lie la liste de sélection à une barre de défilement horizontale. Configurer cette option avec la méthode set() de la barre de défilement. Voir Défilement d’une liste de sélection pour plus d’informations.yscrollcommandSimilaire à l’option précédente mais pour un défilement vertical.Les méthodes des listes de sélection utilisent fréquement des index:
- Si vous utilisez un entier comme index, il se rapporte à la ligne de la liste de sélection qui possède cet index, en comptant à partir de 0.
- L’index 'end' correspond à la dernière ligne de la liste de sélection.
- L’index 'active' correspond à la ligne sélectionnée. Si la liste de sélection permet la multisélection, il correspond à la dernière ligne sélectionnée.
- Un index de la forme '@x,y' correspond à la ligne qui est la plus proche du point de coordonnées (x,y) relativement au coin supérieur gauche du widget.
Les méthodes des listes de sélection incluent:
activate(index)Sélectionne la ligne ayant l’index indiqué.bbox(index) Retourne la boîte englobante - bounding box - de la ligne ayant l’index indiqué sous la forme d’un tuple à 4 éléments (x, y, largeur, hauteur), où le pixel le plus en haut et à gauche de cette ligne est situé en (x,y) et la largeur et hauteur sont données en pixels. La largeur correspond à la partie de la ligne qui contient le texte. Si la ligne de numéro index n’est pas visible, cette méthode retourne None. Si elle est partiellement visible, la boîte englobante peut excéder la zone visible.
curselection() Retourne un tuple qui contient les numéros ou index de la ou des lignes sélectionnées, en comptant à partir de 0. Si aucune ligne n’est sélectionnée, le tuple est vide.
delete(debut, fin=None) Supprime les lignes dont les indices sont dans l’intervalle [debut, fin] (extrémités incluses). Si le deuxième argument est omis, seule la ligne d’index debut est supprimée.
get(debut, fin=None) Retourne un tuple qui contient les textes des lignes dont les indices appartiennent à l’intervalle [deb, fin]. Si le deuxième argument est omis, seul le texte de la ligne d’indice debut est retourné.
index(i) Si c’est possible, positionne la partie visible de la liste de sélection de telle sorte qui la ligne numéro i soit tout en haut de la liste.
insert(index, *elements) Insert une ou plusieurs lignes (autant que d’éléments fournis après le premier argument) dans la liste avant la ligne de numéro index. Utiliser 'end' comme premier argument si vous souhaitez ajouter de nouvelles lignes à la fin de la liste.
itemcget(index, option) Retourne l’une des valeurs d’option de la ligne de numéro index de la liste. Pour les options possibles, voir la méthode itemconfig() ci-dessous. Si l’option donnée n’a pas été configurée pour la ligne indiquée, la valeur de retour est une chaîne vide.
itemconfig(index, option=value, …) Modifie une ou des options de configuration de la ligne de numéro index. Les options incluent:
background – La couleur de fond de la ligne.
foreground – La couleur du texte de la ligne.
selectbackground – La couleur de fond utilisée lorsque la ligne est sélectionnée.
selectforeground – La couleur du texte utilisée lorsque la ligne est sélectionnée.
nearest(y)Retourne l’index de la ligne visible la plus proche du niveau y (vertical) exprimé en pixels relativement au bord supérieur du widget.
scan_dragto(x, y) Voir la méthode scan_mark() ci-dessous.
scan_mark(x, y) Utilisez cette méthode pour implémenter le défilement rapide de la liste de sélection à la souris. Pour réaliser cette fonctionnalité, lier un événement «appui sur l’un des boutons de la souris» à un gestionnaire qui se chargera d’appeler la méthode scan_mark() à la position courante de la souris. Ensuite, lier l’événement «déplacement de la souris» (Motion) à un gestionnaire qui appelera scan_dragto() avec la position courante de la souris. La liste de sélection défilera alors à un rythme proportionnel à la distance qui sépare la position enregisrée par scan_mark et la position courante.
see(index) Ajuste la position de la liste de sélection de telle sorte que la ligne de numéro index soit visible.
selection_anchor(index) Positionne l’«ancre de sélection» sur la ligne de numéro index. Une fois que cette ancre a été positionnée, vous pouvez y faire référence en utilisant l’index spécial 'anchor'. Par exemple, si votre liste est lbox, ces instructions sélectionnerons les lignes 3, 4 et 5:
lbox.selection_anchor(3) lbox.selection_set(tk.ANCHOR,5)
selection_clear(debut, fin=None) Déselectionne toutes les lignes dont les index appartiennent à l’intervalle [debut, fin]. Si le second argument est omis, seule la ligne de numéro debut est déselectionnée.
selection_includes(index) Retourne 1 si la ligne d’index donné est sélectionnée et retourne 0 autrement.
selection_set(debut, fin=None) Sélectionne toute les lignes dont les index appartiennent à l’intervalle [debut, fin]. Si le deuxième argument est omis, seule la ligne d’index debut est sélectionnée.
size() Retourne le nombre de lignes de la liste de sélection.
xview() Pour faire défiler la liste horizontalement, configurez l’option command du widget barre de défilement horizontale avec cette méthode. Voir Défilement d’une liste de sélection.
xview_moveto(fraction) Fait défiler la liste de sélection horizontalement de telle sorte que le côté gauche de la fraction de sa ligne la plus longue soit placé contre le bord gauche de la zone visible. L’argument fraction appartient à l’intervalle [0,1].
xview_scroll(nombre, quoi) Fait défiler la liste de sélection horizontalement. Pour l’argument quoi, utiliser soit 'units' pour un défilement d’unité «un caractère», ou 'pages' pour un défilement où l’unité est la «largeur effective de la liste de sélection». L’argument nombre indique le nombre d’unités du défilement: les valeurs négatives font défiler vers la droite, les positives vers la gauche.
yview() Similaire à la méthode xview(), mais pour un défilement vertical.
yview_moveto(fraction) Similaire à la méthode xview_moveto() pour un défilement vertical.
yview_scroll(nombre, quoi) Similaire à la méthode xview_scroll() mais pour un défilement vertical. 'units' se réfère à l’unité «ligne» et 'pages' à l’unité «hauteur visible de la liste».
Créer des barres de défilement scrollbar
Voici un fragment de code qui illustre la création et la liaison d’une liste de sélection avec des barres de défilement verticale et horizontale:
yDefilB = Scrollbar(root, orient='vertical') yDefilB.grid(row=0, column=1, sticky='ns') xDefilB = Scrollbar(root, orient='horizontal') xDefilB.grid(row=1, column=0, sticky='ew') listSel = Listbox(root, xscrollcommand=xDefilB.set, yscrollcommand=yDefilB.set) listSel.grid(row=0, column=0, sticky='nsew') xDefilB['command'] = listSel.xview yDefilB['command'] = listSel.yview
—
LISTBOX
Une listbox ne peut contenir que du texte (de même couleurs et police). Suivant la config, on peut sélectionner un ou plusieurs item.
When you first create the listbox, it is empty. The first thing to do is usually to insert one or more lines of text. The insert method takes an index and a string to insert. The index is usually an item number (0 for the first item in the list), but you can also use some special indexes, including ACTIVE, which refers to the “active” item (set when you click on an item, or by the arrow keys), and END, which is used to append items to the list :
import tkinter w = Tk() listbox = tk.Listbox(w) listbox.pack() listbox.insert(END, "une première ligne") for item in ["un", "deux", "trois", "quatre"]: listbox.insert(END, item) mainloop()
To remove items from the list, use the delete method. The most common operation is to delete all items in the list (something you often need to do when updating the list).
listbox.delete(0, END) listbox.insert(END, newitem)
You can also delete individual items. In the following example, a separate button is used to delete the ACTIVE item from a list.
lb = Listbox(master) b = Button(master, text="Delete", command=lambda lb=lb: lb.delete(ANCHOR))
The listbox offers four different selection modes through the selectmode option. These are SINGLE (just a single choice), BROWSE (same, but the selection can be moved using the mouse), MULTIPLE (multiple item can be choosen, by clicking at them one at a time), or EXTENDED (multiple ranges of items can be chosen, using the Shift and Control keyboard modifiers). The default is BROWSE. Use MULTIPLE to get “checklist” behavior, and EXTENDED when the user would usually pick only one item, but sometimes would like to select one or more ranges of items.
lb = Listbox(selectmode=EXTENDED)
To query the selection, use curselection method. It returns a list of item indexes, but a bug in Tkinter 1.160 (Python 2.2) and earlier versions causes this list to be returned as a list of strings, instead of integers. This may be fixed in later versions of Tkinter, so you should make sure that your code is written to handle either case. Here’s one way to do that:
items = map(int, list.curselection())
In versions before Python 1.5, use string.atoi instead of int.
Use the get method to get the list item corresponding to a given index. Note that get accepts either strings or integers, so you don’t have to convert the indexes to integers if all you’re going to do is to pass them to get.
You can also use a listbox to represent arbitrary Python objects. In the next example, we assume that the input data is represented as a list of tuples, where the first item in each tuple is the string to display in the list. For example, you could display a dictionary by using the items method to get such a list.
self.lb.delete(0, END) # clear for key, value in data: self.lb.insert(END, key) self.data = data
When querying the list, simply fetch the items from the data attribute, using the selection as an index:
items = self.lb.curselection() items = [self.data[int(item)] for item in items]
In earlier versions of Python, you can use this instead:
items = self.lb.curselection() try: items = map(int, items) except ValueError: pass items = map(lambda i,d=self.data: d[i], items)
Unfortunately, the listbox doesn’t provide a command option allowing you to track changes to the selection. The standard solution is to bind a double-click event to the same callback as the OK (or Select, or whatever) button. This allows the user to either select an alternative as usual, and click OK to carry out the operation, or to select and carry out the operation in one go by double-clicking on an alternative. This solution works best in BROWSE and EXTENDED modes.
lb.bind("<Double-Button-1>", self.ok)
If you wish to track arbitrary changes to the selection, you can either rebind the whole bunch of selection related events (see the Tk manual pages for a complete list of Listbox event bindings), or, much easier, poll the list using a timer:
class Dialog(Frame): def __init__(self, master): Frame.__init__(self, master) self.list = Listbox(self, selectmode=EXTENDED) self.list.pack(fill=BOTH, expand=1) self.current = None self.poll() # start polling the list def poll(self): now = self.list.curselection() if now != self.current: self.list_has_changed(now) self.current = now self.after(250, self.poll) def list_has_changed(self, selection): print "selection is", selection
By default, the selection is exported via the X selection mechanism (or the clipboard, on Windows). If you have more than one listbox on the screen, this really messes things up for the poor user. If she selects something in one listbox, and then selects something in another, the original selection disappears. It is usually a good idea to disable this mechanism in such cases. In the following example, three listboxes are used in the same dialog:
b1 = Listbox(exportselection=0) for item in families: b1.insert(END, item) b2 = Listbox(exportselection=0) for item in fonts: b2.insert(END, item) b3 = Listbox(exportselection=0) for item in styles: b3.insert(END, item)
The listbox itself doesn’t include a scrollbar. Attaching a scrollbar is pretty straightforward. Simply set the xscrollcommand and yscrollcommand options of the listbox to the set method of the corresponding scrollbar, and the command options of the scrollbars to the corresponding xview and yview methods in the listbox. Also remember to pack the scrollbars before the listbox. In the following example, only a vertical scrollbar is used. For more examples, see pattern section in the Scrollbar description.
frame = Frame(master) scrollbar = Scrollbar(frame, orient=VERTICAL) listbox = Listbox(frame, yscrollcommand=scrollbar.set) scrollbar.config(command=listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) listbox.pack(side=LEFT, fill=BOTH, expand=1)
Reference
Listbox(master, **options) A scrolling listbox.
**options
activate(index) Activates the given index (it will be marked with an underline). The active item can be refered to using the ACTIVE index.
index Index specifier.
bbox(self, index) Gets the bounding box of the given item text.
index Index specifier.
Returns: The bounding box, as a 4-tuple (xoffset, yoffset, width, height). If the item is not visible, this method returns None. If the item is partially visible, the box may extend outside the visible area.
config(**options) Modifies one or more widget options. If no options are given, the method returns a dictionary containing all current option values.
activestyle= Default is underline. (the option database name is activeStyle, the class is ActiveStyle)
background= ou bg= Default value is ‘SystemButtonFace’. (background/Background)
borderwidth= ou bd= Default value is 2. (borderWidth/BorderWidth)
cursor= No default value. (cursor/Cursor)
disabledforeground= Default is system specific. (disabledForeground/DisabledForeground)
exportselection= Default value is 1. (exportSelection/ExportSelection)
font= Default value is system specific. (font/Font)
foreground= ou fg=Default value is system specific. (foreground/Foreground)
height= Default value is 10. (height/Height)
highlightbackground= Default value is system specific. (highlightBackground/HighlightBackground)
highlightcolor= Default value is system specific. (highlightColor/HighlightColor)
highlightthickness= Default value is 1. (highlightThickness/HighlightThickness)
listvariable= No default value. (listVariable/Variable)
relief= Default is SUNKEN. (relief/Relief)
selectbackground= Default is system specific. (selectBackground/Foreground)
selectborderwidth= Default is 1. (selectBorderWidth/BorderWidth)
selectforeground= Default is system specific. (selectForeground/Background)
selectmode= Default is BROWSE. (selectMode/SelectMode)
setgrid= Default is 0. (setGrid/SetGrid)
state= Default is NORMAL. (state/State)
takefocus= No default value. (takeFocus/TakeFocus)
width= Default is 20. (width/Width)
xscrollcommand= No default value. (xScrollCommand/ScrollCommand)
yscrollcommand= No default value. (yScrollCommand/ScrollCommand)
curselection() Gets a list of the currently selected alternatives. The list contains the indexes of the selected alternatives (beginning with 0 for the first alternative in the list).
In most Python versions, the list contains strings instead of integers. Since this may change in future versions, you should make sure your code can handle either case. See the patterns section for a suggested solution.
Returns: A list of index specifiers.
delete(first, last=None) Deletes one or more items. Use delete(0, END) to delete all items in the list.
first First item to delete.
last Last item to delete. If omitted, a single item is deleted.
get(first, last=None) Gets one or more items from the list. This function returns the string corresponding to the given index (or the strings in the given index range). Use get(0, END) to get a list of all items in the list. Use get(ACTIVE) to get the active (underlined) item.
first First item to return.
last Last item to return. If omitted, a single item is returned.
Returns: A list of strings.
index(index) Returns the numerical index (0 to size()-1) corresponding to the given index. This is typically ACTIVE, but can also be ANCHOR, or a string having the form “@x,y” where x and y are widget-relative pixel coordinates.
index Index specifier.
Returns: Numerical index.
insert(index, *elements) Inserts one or more items at given index (this works as for Python lists; index 0 is before the first item). Use END to append items to the list. Use ACTIVE to insert items before the the active (underlined) item.
index Index specifier.
*elements One or more elements to add.
itemconfig(index, **options) Modifies the configuration for an individual listbox item.
**options
nearest(y) Returns the index nearest to the given coordinate (a widget-relative pixel coordinate).y Coordinate.Returns:An index.
scan_dragto(x, y) Scrolls the widget contents according to the given mouse coordinate. The text is moved 10 times the distance between the scanning anchor and the new position.x Mouse coordinate.y Mouse coordinate.
scan_mark(x, y) Sets the scanning anchor for fast horizontal scrolling to the given mouse coordinate.
x Mouse coordinate.y Mouse coordinate.
see(index) Makes sure the given list index is visible. You can use an integer index, or END.
index Index specifier.
select_anchor(index) Sets the selection anchor to the given index. The anchor can be refered to using the ANCHOR index.
index Index specifier.
select_clear(first, last=None) Removes one or more items from the selection.
first First item to remove.
last Last item to remove. If omitted, only one item is removed.
select_includes(index) Checks if an item is selected.
index Index specifier.
Returns:A true value if the item is selected.
select_set(first, last=None) Adds one or more items to the selection.
first First item to add.
last Last item to add. If omitted, only one item is added.
size() Returns the number of items in the list. The valid index range goes from 0 to size()-1.
Returns:The number of items in this list.
xview(column, *extra) Controls horizontal scrolling.
If called without an arguement, this method determines which part of the full list that is visible in the horizontal direction. This is given as the offset and size of the visible part, given in relation to the full size of the list (1.0 is the full list).
If called with a single argument, this method adjusts the list so that the given character column is at the left edge of the listbox.
If called with the string “moveto” and a fraction, this method behaves like xview_moveto. If called with the string “scroll” and two more arguments, this method behaves like xview_scroll.
column The column to place at the left edge, or a string specifying what subcommand to execute.
*extra Additional arguments for the “moveto” and “scroll” forms. See above for details.
Returns:If called without any arguments, a 2-tuple containing the left offset and the view size (relative to the full width).
xview_moveto(fraction) Adjusts the list so that the given offset is at the left (top) edge of the listbox. Offset 0.0 is the beginning of the list, 1.0 the end. These methods are used by the Scrollbar bindings when the user drags the scrollbar slider.
fraction Offset.
xview_scroll(number, what) Scrolls the list view horizontally by the given amount.
number Number of units.
what What unit to use. This can be either “units” (characters) or “pages” (larger steps).
yview(*what) Controls vertical scrolling. This method works like xview, but controls vertical scrolling.
To make sure that a given item is visible, use the see method.
index The index to place at the top edge, or a string specifying what subcommand to execute.
*extra Additional arguments for the “moveto” and “scroll” forms.
Returns:If called without any arguments, a 2-tuple containing the top offset and the view size (relative to the list size).
yview_moveto(fraction) Adjusts the list view so that the given offset is at the left edge of the canvas. Offset 0.0 is the beginning of the entry string, 1.0 the end.
fraction Offset.
yview_scroll(number, what) Scrolls the list view vertically by the given amount.
number Number of units.
what What unit to use. This can be either “units” (characters) or “pages” (larger steps).
—
RADIOBUTTON
Peut contenir du texte ou des images. Lorsque le button is pressed, Tkinter automatically calls that function or method.
The button can only display text in a single font, but the text may span more than one line. In addition, one of the characters can be underlined, for example to mark a keyboard shortcut. By default, the Tab key can be used to move to a button widget.
Each group of Radiobutton widgets should be associated with single variable. Each button then represents a single value for that variable.
Patterns
To get a proper radio behavior, make sure to have all buttons in a group point to the same variable, and use the value option to specify what value each button represents:
from Tkinter import * w = Tk() v = IntVar() Radiobutton(w, text="One", variable=v, value=1).pack(anchor=W) Radiobutton(w, text="Two", variable=v, value=2).pack(anchor=W) mainloop()
If you need to get notified when the value changes, attach a command callback to each button.
To create a large number of buttons, use a loop:
MODES = [ ("Monochrome", "1"), ("Grayscale", "L"), ("True color", "RGB"), ("Color separation", "CMYK"), ] v = StringVar() v.set("L") # initialize for text, mode in MODES: b = Radiobutton(w, text=text, variable=v, value=mode) b.pack(anchor=W)
Figure: Standard radiobuttons
To turn the above example into a “button box” rather than a set of radio buttons, set the indicatoron option to 0. In this case, there’s no separate radio button indicator, and the selected button is drawn as SUNKEN instead of RAISED:
Figure: Using indicatoron=0
Reference
Radiobutton(master=None, **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.
activebackground= What background color to use when the button is active. The default is system specific.
activeforeground= What foreground color to use when the button is active. The default is system specific
anchor= Controls where in the button the text (or image) should be located. Use one of N, NE, E, SE, S, SW, W, NW, or CENTER. Default is CENTER.
background= ou bg=The background color. The default is system specific.
bitmap= The bitmap to display in the widget. If the image option is given, this option is ignored.
borderwidth= ou bd= The width of the button border. The default is platform specific, but is usually 1 or 2 pixels.
command= A function or method that is called when the button is pressed. The callback can be a function, bound method, or any other callable Python object.
compound= Controls how to combine text and image in the button. By default, if an image or bitmap is given, it is drawn instead of the text. If this option is set to CENTER, the text is drawn on top of the image. If this option is set to one of BOTTOM, LEFT, RIGHT, or TOP, the image is drawn besides the text (use BOTTOM to draw the image under the text, etc.). Default is NONE.
cursor= The cursor to show when the mouse is moved over the button.
disabledforeground= The color to use when the button is disabled. The background is shown in the background color. The default is system specific.
font= The font to use in the button. The button can only contain text in a single font. The default is system specific.
foreground= ou fg=The color to use for text and bitmap content. The default is system specific.
height= The height of the button. If the button displays text, the size is given in text units. If the button displays an image, the size is given in pixels (or screen units). If the size is omitted, it is calculated based on the button contents
highlightbackground= The color to use for the highlight border when the button does not have focus. The default is system specific.
highlightcolor= The color to use for the highlight border when the button has focus. The default is system speciific.
highlightthickness= The width of the highlight border. The default is system specific (usually one or two pixels).
image= The image to display in the widget. If specified, this takes precedence over the text and bitmap options.
indicatoron= If true, the widget uses the standard radio button look. If false, the selected button is drawn as SUNKEN instead. Default is true.
justify= Defines how to align multiple lines of text. Use LEFT, RIGHT, or CENTER. Default is CENTER.
offrelief= Default is raised.
overrelief= Alternative relief to use when the mouse is moved over the widget. If empty, always use the relief value.
padx= Extra horizontal padding between the text or image and the border.
pady= Extra vertical padding between the text or image and the border.
relief= Border decoration. One of SUNKEN, RAISED, GROOVE, RIDGE, or FLAT. Default is FLAT if indicatoron is true, otherwise RAISED. (relief/Relief)
selectcolor= Default value is ‘SystemWindow’.
selectimage= No default value.
state= The button state: NORMAL, ACTIVE or DISABLED. Default is NORMAL.
takefocus= Indicates that the user can use the Tab key to move to this button. Default is an empty string, which means that the button accepts focus only if it has any keyboard bindings (default is on, in other words).
text= The text can contain newlines. If the bitmap or image options are used, this option is ignored (unless the compound option is used).
textvariable= Associates a Tkinter variable (usually a StringVar) to the button. If the variable is changed, the button text is updated.
underline= Which character to underline, in a text label. Default is -1, which means that no character is underlined.
value= The value associated with this radiobutton. All buttons in the same group should have distinct values.
variable= The variable that’s associated with this button. To get proper radio behaviour, you need to associate the same variable to all buttons in the same group.
width= The width of the button. If the button displays text, the size is given in text units. If the button displays an image, the size is given in pixels (or screen units). If the size is omitted, or zero, it is calculated based on the button contents.
wraplength= Determines when a button’s text should be wrapped into multiple lines. This is given in screen units. Default is 0 (no wrapping).
deselect() Deselects the button.
flash() Redraws the button a couple of times, alternating between active and normal appearance. This can be useful when debugging, or to indicate when some other user action has activate the button.
invoke() Calls the command associated with the button.
select() Selects the button.
—