Tkinter 8.4 Reference - A GUI For Python (2010) PDF
Tkinter 8.4 Reference - A GUI For Python (2010) PDF
Abstract
Describes the Tkinter widget set for constructing graphical user interfaces (GUIs) in the Python programming language. This publication is available in Web form1 and also as a PDF document2. Please forward any comments to tcc-doc@nmt.edu.
Table of Contents
1. What is Tkinter? ....................................................................................................................... 3 2. A minimal application .............................................................................................................. 3 3. Definitions .............................................................................................................................. 4 4. Layout management ................................................................................................................. 5 4.1. The .grid() method .................................................................................................... 5 4.2. Other grid management methods ................................................................................... 6 4.3. Configuring column and row sizes ................................................................................. 7 4.4. Making the root window resizeable ................................................................................ 8 5. Standard attributes ................................................................................................................... 8 5.1. Dimensions ................................................................................................................... 9 5.2. The coordinate system ................................................................................................... 9 5.3. Colors ........................................................................................................................... 9 5.4. Type fonts ................................................................................................................... 10 5.5. Anchors ...................................................................................................................... 11 5.6. Relief styles ................................................................................................................. 12 5.7. Bitmaps ....................................................................................................................... 12 5.8. Cursors ....................................................................................................................... 12 5.9. Images ........................................................................................................................ 14 5.10. Geometry strings ........................................................................................................ 14 5.11. Window names ........................................................................................................... 15 5.12. Cap and join styles ..................................................................................................... 15 5.13. Dash patterns ............................................................................................................. 16 5.14. Matching stipple patterns ............................................................................................ 16 6. The Button widget ................................................................................................................ 17 7. The Canvas widget ................................................................................................................ 19 7.1. Canvas coordinates ...................................................................................................... 20 7.2. The Canvas display list ................................................................................................ 20 7.3. Canvas object IDs ........................................................................................................ 21 7.4. Canvas tags ................................................................................................................ 21
1 2
http://www.nmt.edu/tcc/help/pubs/tkinter/ http://www.nmt.edu/tcc/help/pubs/tkinter/tkinter.pdf
Tkinter reference
7.5. Canvas tagOrId arguments ...................................................................................... 21 7.6. Methods on Canvas widgets ........................................................................................ 21 7.7. Canvas arc objects ....................................................................................................... 26 7.8. Canvas bitmap objects ................................................................................................. 28 7.9. Canvas image objects .................................................................................................. 29 7.10. Canvas line objects ..................................................................................................... 29 7.11. Canvas oval objects .................................................................................................... 31 7.12. Canvas polygon objects .............................................................................................. 32 7.13. Canvas rectangle objects ............................................................................................. 34 7.14. Canvas text objects ..................................................................................................... 35 7.15. Canvas window objects .............................................................................................. 36 8. The Checkbutton widget ...................................................................................................... 37 9. The Entry widget .................................................................................................................. 40 9.1. Scrolling an Entry widget ............................................................................................ 43 10. The Frame widget ................................................................................................................ 43 11. The Label widget ................................................................................................................ 44 12. The LabelFrame widget ...................................................................................................... 46 13. The Listbox widget ............................................................................................................ 48 13.1. Scrolling a Listbox widget ........................................................................................ 52 14. The Menu widget .................................................................................................................. 52 14.1. Menu item creation (coption) options ......................................................................... 55 15. The Menubutton widget ...................................................................................................... 56 16. The Message widget ............................................................................................................ 58 17. The OptionMenu widget ....................................................................................................... 59 18. The PanedWindow widget .................................................................................................... 60 18.1. PanedWindow child configuration options ................................................................... 63 19. The Radiobutton widget .................................................................................................... 63 20. The Scale widget ................................................................................................................ 66 21. The Scrollbar widget ........................................................................................................ 69 21.1. The Scrollbar command callback ............................................................................ 72 21.2. Connecting a Scrollbar to another widget ................................................................ 73 22. The Spinbox widget ............................................................................................................ 73 23. The Text widget .................................................................................................................. 77 23.1. Text widget indices ................................................................................................... 80 23.2. Text widget marks .................................................................................................... 81 23.3. Text widget images ................................................................................................... 82 23.4. Text widget windows ............................................................................................... 82 23.5. Text widget tags ....................................................................................................... 82 23.6. Setting tabs in a Text widget ...................................................................................... 82 23.7. The Text widget undo/redo stack .............................................................................. 83 23.8. Methods on Text widgets .......................................................................................... 83 24. Toplevel: Top-level window methods .................................................................................. 90 25. Universal widget methods ..................................................................................................... 93 26. Standardizing appearance ................................................................................................... 100 26.1. How to name a widget class ...................................................................................... 101 26.2. How to name a widget instance ................................................................................. 101 26.3. Resource specification lines ....................................................................................... 102 26.4. Rules for resource matching ...................................................................................... 103 27. Connecting your application logic to the widgets ................................................................... 103 28. Control variables: the values behind the widgets ................................................................... 104 29. Focus: routing keyboard input ............................................................................................. 106 30. Events ................................................................................................................................ 107
Tkinter reference
30.1. Levels of binding ...................................................................................................... 30.2. Event sequences ....................................................................................................... 30.3. Event types .............................................................................................................. 30.4. Event modifiers ........................................................................................................ 30.5. Key names ............................................................................................................... 30.6. Writing your handler: The Event class ...................................................................... 30.7. The extra arguments trick .......................................................................................... 30.8. Virtual events ........................................................................................................... 31. Pop-up dialogs .................................................................................................................... 31.1. The tkMessageBox dialogs module .......................................................................... 31.2. The tkFileDialog module ..................................................................................... 31.3. The tkColorChooser module .................................................................................
107 108 109 110 110 113 114 115 116 116 117 118
1. What is Tkinter?
Tkinter is a GUI (graphical user interface) widget set for Python. This document contains only the commoner features. This document applies to Python 2.5 and Tkinter 8.4 running in the X Window system under Linux. Your version may vary. Pertinent references: Fredrik Lundh, who wrote Tkinter, has two versions of his An Introduction to Tkinter: a more complete 1999 version3 and a 2005 version4 that presents a few newer features. Python and Tkinter Programming by John Grayson (Manning, 2000, ISBN 1-884777-81-3) is out of print, but has many useful examples and also discusses an extension package called Pmw: Python megawidgets5. Python 2.5 quick reference6: general information about the Python language. For an example of a sizeable working application (around 1000 lines of code), see huey: A color and font selection tool7. We'll start by looking at the visible part of Tkinter: creating the widgets and arranging them on the screen. Later we will talk about how to connect the facethe front panelof the application to the logic behind it.
2. A minimal application
Here is a trivial Tkinter program containing only a Quit button: #!/usr/local/bin/python from Tkinter import *
1 2 3 4
Tkinter reference
self.grid() self.createWidgets()
This line makes the script self-executing, assuming that your system has the Python interpreter at path /usr/local/bin/python. This line imports the entire Tkinter package into your program's namespace. Your application class must inherit from Tkinter's Frame class. Calls the constructor for the parent class, Frame. Necessary to make the application actually appear on the screen. Creates a button labeled Quit. Places the button on the application. The main program starts here by instantiating the Application class. This method call sets the title of the window to Sample application. Starts the application's main loop, waiting for mouse and keyboard events.
3. Definitions
Before we proceed, let's define some of the common terms. window This term has different meanings in different contexts, but in general it refers to a rectangular area somewhere on your display screen. top-level window A window that exists independently on your screen. It will be decorated with the standard frame and controls for your system's desktop manager. You can move it around on your desktop. You can generally resize it, although your application can prevent this widget The generic term for any of the building blocks that make up an application in a graphical user interface. Examples of widgets: buttons, radiobuttons, text fields, frames, and text labels. frame In Tkinter, the Frame widget is the basic unit of organization for complex layouts. A frame is a rectangular area that can contain other widgets. child, parent When any widget is created, a parent-child relationship is created. For example, if you place a text label inside a frame, the frame is the parent of the label.
Tkinter reference
4. Layout management
Later we will discuss the widgets, the building blocks of your GUI application. How do widgets get arranged in a window? Although there are three different geometry managers in Tkinter, the author strongly prefers the .grid() geometry manager for pretty much everything. This manager treats every window or frame as a tablea gridwork of rows and columns. A cell is the area at the intersection of one row and one column. The width of each column is the width of the widest cell in that column. The height of each row is the height of the largest cell in that row. For widgets that do not fill the entire cell, you can specify what happens to the extra space. You can either leave the extra space outside the widget, or stretch the widget to fit it, in either the horizontal or vertical dimension. You can combine multiple cells into one larger area, a process called spanning. When you create a widget, it does not appear until you register it with a geometry manager. Hence, construction and placing of a widget is a two-step process that goes something like this: self.thing = Constructor(parent, ...) self.thing.grid(...) where Constructor is one of the widget classes like Button, Frame, and so on, and parent is the parent widget in which this child widget is being constructed. All widgets have a .grid() method that you can use to tell the geometry manager where to put it.
columnspan Normally a widget occupies only one cell in the grid. However, you can grab multiple cells of a row and merge them into one larger cell by setting the columnspan option to the number of cells. For example, w.grid(row=0, column=2, columnspan=3) would place widget w in a cell that spans columns 2, 3, and 4 of row 0. in_ ipadx ipady padx To register w as a child of some widget w2, use in_=w2. The new parent w2 must be a descendant of the parent widget used when w was created. Internal x padding. This dimension is added inside the widget inside its left and right sides. Internal y padding. This dimension is added inside the widget inside its top and bottom borders. External x padding. This dimension is added to the left and right outside the widget.
Tkinter reference
External y padding. This dimension is added above and below the widget. The row number into which you want to insert the widget, counting from 0. The default is the next higher-numbered unoccupied row. Normally a widget occupies only one cell in the grid. You can grab multiple adjacent cells of a column, however, by setting the rowspan option to the number of cells to grab. This option can be used in combination with the columnspan option to grab a block of cells. For example, w.grid(row=3, column=2, rowspan=4, columnspan=5) would place widget w in an area formed by merging 20 cells, with row numbers 36 and column numbers 26. This option determines how to distribute any extra space within the cell that is not taken up by the widget at its natural size. See below.
sticky
If you do not provide a sticky attribute, the default behavior is to center the widget in the cell. You can position the widget in a corner of the cell by using sticky=NE (top right), SE (bottom right), SW (bottom left), or NW (top left). You can position the widget centered against one side of the cell by using sticky=N (top center), E (right center), S (bottom center), or W (left center). Use sticky=N+S to stretch the widget vertically but leave it centered horizontally. Use sticky=E+W to stretch it horizontally but leave it centered vertically. Use sticky=N+E+S+W to stretch the widget both horizontally and vertically to fill the cell. The other combinations will also work. For example, sticky=N+S+W will stretch the widget vertically and place it against the west (left) wall.
Tkinter reference
w.grid_propagate() Normally, all widgets propagate their dimensions, meaning that they adjust to fit the contents. However, sometimes you want to force a widget to be a certain size, regardless of the size of its contents. To do this, call w.grid_propagate(0) where w is the widget whose size you want to force. w.grid_remove() This method is like .grid_forget(), but its grid options are remembered, so if you .grid() it again, it will use the same grid configuration options. w.grid_size() Returns a 2-tuple containing the number of columns and the number of rows, respectively, in w's grid system. w.grid_slaves ( row=None, column=None ) Returns a list of the widgets managed by widget w. If no arguments are provided, you will get a list of all the managed widgets. Use the row= argument to select only the widgets in one row, or the column= argument to select only the widgets in one column.
Tkinter reference
2 3 4 5 6
The top level window is the outermost window on the screen. However, this window is not your Application windowit is the parent of the Application instance. To get the top-level window, call the .winfo_toplevel() method on any widget in your application; see Section 25, Universal widget methods (p. 93). This line makes row 0 of the top level window's grid stretchable. This line makes column 0 of the top level window's grid stretchable. Makes row 0 of the Application widget's grid stretchable. Makes column 0 of the Application widget's grid stretchable. The argument sticky=N+S+E+W makes the button expand to fill its cell of the grid.
There is one more change that must be made. In the constructor, change the second line as shown: def __init__(self, master=None): Frame.__init__(self, master) self.grid(sticky=N+S+E+W) self.createWidgets() The argument sticky=N+S+E+W to self.grid() is necessary so that the Application widget will expand to fill its cell of the top-level window's grid.
5. Standard attributes
Before we look at the widgets, let's take a look at how some of their common attributessuch as sizes, colors and fontsare specified. Each widget has a set of options that affect its appearance and behaviorattributes such as fonts, colors, sizes, text labels, and such.
Tkinter reference
You can specify options when calling the widget's constructor using keyword arguments such as text="PANIC!" or height=20. After you have created a widget, you can later change any option by using the widget's .config() method. You can retrieve the current setting of any option by using the widget's .cget() method. See Section 25, Universal widget methods (p. 93) for more on these methods.
5.1. Dimensions
Various lengths, widths, and other dimensions of widgets can be described in many different units. If you set a dimension to an integer, it is assumed to be in pixels. You can specify units by setting a dimension to a string containing a number followed by: c Centimeters i Inches m Millimeters p Printer's points (about 1/72")
+x
+y
The base unit is the pixel, with the top left pixel having coordinates (0,0). Coordinates that you specify as integers are always expressed in pixels, but any coordinate may be specified as a dimensioned quantity; see Section 5.1, Dimensions (p. 9).
5.3. Colors
There are two general ways to specify colors in Tkinter. You can use a string specifying the proportion of red, green, and blue in hexadecimal digits: #rgb #rrggbb Four bits per color Eight bits per color
#rrrgggbbb Twelve bits per color For example, '#fff' is white, '#000000' is black, '#000fff000' is pure green, and '#00ffff' is pure cyan (green plus blue). You can also use any locally defined standard color name. The colors "white", "black", "red", "green", "blue", "cyan", "yellow", and "magenta" will always be available. Other names may work, depending on your local installation.
Tkinter reference
overstrike 1 for overstruck text, 0 for normal. For example, to get a 36-point bold Helvetica italic face: helv36 = tkFont.Font ( family="Helvetica", size=36, weight="bold" ) If you are running under the X Window System, you can use any of the X font names. For example, the font named "-*-lucidatypewriter-medium-r-*-*-*-140-*-*-*-*-*-*" is the author's favorite fixed-width font for onscreen use. Use the xfontsel program to help you select pleasing fonts. To get a list of all the families of fonts available on your platform, call this function: tkFont.families() The return value is a list of strings. Note: You must create your root window before calling this function. These methods are defined on all Font objects: .actual ( option=None ) If you pass no arguments, you get back a dictionary of the font's actual attributes, which may differ from the ones you requested. To get back the value of an attribute, pass its name as an argument. .cget ( option ) Returns the value of the given option. .configure ( option, ... ) Use this method to change one or more options on a font. For example, if you have a Font object called titleFont, if you call titleFont.configure ( family="times", size=18 ), that font will change to 18pt Times and any widgets that use that font will change too. .copy() Returns a copy of a Font object.
10
Tkinter reference
.measure ( text ) Pass this method a string, and it will return the number of pixels of width that string will take in the font. Warning: some slanted characters may extend outside this area. .metrics ( option ) If you call this method with no arguments, it returns a dictionary of all the font metrics. You can retrieve the value of just one metric by passing its name as an argument. Metrics include: ascent descent fixed Number of pixels of height between the baseline and the top of the highest ascender. Number of pixels of height between the baseline and the bottom of the lowest ascender. This value is 0 for a variable-width font and 1 for a monospaced font.
linespace Number of pixels of height total. This is the leading of type set solid in the given font.
5.5. Anchors
The Tkinter package defines a number of anchor constants that you can use to control where items are positioned relative to their context. For example, anchors can specify where a widget is located inside a frame when the frame is bigger than the widget. These constants are given as compass points, where north is up and west is to the left. We apologize to our Southern Hemisphere readers for this Northern Hemisphere chauvinism8. The anchor constants are shown in this diagram:
NW
NE
CENTER
SW
SE
For example, if you create a small widget inside a large frame and use the anchor=SE option, the widget will be placed in the bottom right corner of the frame. If you used anchor=N instead, the widget would be centered along the top edge. Anchors are also used to define where text is positioned relative to a reference point. For example, if you use CENTER as a text anchor, the text will be centered horizontally and vertically around the reference point. Anchor NW will position the text so that the reference point coincides with the northwest (top left) corner of the box containing the text. Anchor W will center the text vertically around the reference point, with the left edge of the text box passing through that point, and so on.
http://flourish.org/upsidedownmap/
Tkinter reference
11
The width of these borders depends on the borderwidth attribute of the widget. The above graphic shows what they look like with a 5-pixel border; the default border width is 2.
5.7. Bitmaps
For bitmap options in widgets, these bitmaps are guaranteed to be available:
The graphic above shows Button widgets bearing the standard bitmaps. From left to right, they are "error", "gray75", "gray50", "gray25", "gray12", "hourglass", "info", "questhead", "question", and "warning". You can use your own bitmaps. Any file in .xbm (X bit map) format will work. In place of a standard bitmap name, use the string "@" followed by the pathname of the .xbm file.
5.8. Cursors
There are quite a number of different mouse cursors available. Their names and graphics are shown here. The exact graphic may vary according to your operating system. arrow based_arrow_down based_arrow_up boat bogosity bottom_left_corner bottom_right_corner bottom_side bottom_tee box_spiral center_ptr man middlebutton mouse pencil pirate plus question_arrow right_ptr right_side right_tee rightbutton
12
Tkinter reference
circle clock coffee_mug cross cross_reverse crosshair diamond_cross dot dotbox double_arrow draft_large draft_small draped_box exchange fleur gobbler gumby hand1 hand2 heart icon iron_cross left_ptr left_side left_tee leftbutton
rtl_logo sailboat sb_down_arrow sb_h_double_arrow sb_left_arrow sb_right_arrow sb_up_arrow sb_v_double_arrow shuttle sizing spider spraycan star target tcross top_left_arrow top_left_corner top_right_corner top_side top_tee trek ul_angle umbrella ur_angle watch xterm
Tkinter reference
13
ll_angle lr_angle
X_cursor
5.9. Images
There are three general methods for displaying graphic images in your Tkinter application. To display bitmap (two-color) images in the .xbm format, refer to Section 5.9.1, The BitmapImage class (p. 14). To display full-color images in the .gif, .pgm, or .ppm format, see Section 5.9.2, The PhotoImage class (p. 14). The Python Imaging Library (PIL) supports images in a much wider variety of formats. Its ImageTk class is specifically designed for displaying images within Tkinter applications. See the author's companion document for PIL documentation: Python Imaging Library (PIL) quick reference9.
http://www.nmt.edu/tcc/help/pubs/pil/
14
Tkinter reference
"wxhxy" where: The w and h parts give the window width and height in pixels. They are separated by the character "x". If the next part has the form +x, it specifies that the left side of the window should be x pixels from the left side of the desktop. If it has the form -x, the right side of the window is x pixels from the right side of the desktop. If the next part has the form +y, it specifies that the top of the window should be y pixels below the top of the desktop. If it has the form -y, the bottom of the window will be y pixels above the bottom edge of the desktop. For example, a window created with geometry="120x50-0+20" would be 120 pixels wide by 50 pixels high, and its top right corner will be along the right edge of the desktop and 20 pixels below the top edge.
Tkinter reference
15
The join style describes the shape where two line segments meet at an angle. ROUND: The join is a circle centered on the point where the adjacent line segments meet. BEVEL: A flat facet is drawn at an angle intermediate between the angles of the adjacent lines. MITER: The edges of the adjacent line segments are continued to meet at a sharp point. This illustration shows Tkinter's cap and join options. Small red squares indicate the nominal endpoints of the two connected line segments.
16
Tkinter reference
Here is an example. The left-hand screen shot shows two adjacent 100100 squares stippled with the gray12 pattern, but the right-hand square is offset vertically by one pixel. The short black line in the center of the figure is drawn along the boundary of the two figures.
The second screen shot is the same, except that the two 100100 squares have their stipple patterns lined up. In practice, this arises in two situations. The alignment of large stippled areas is controlled by an option named offset. For figures with stippled outlines, the outlineoffset option controls their alignment. Both options have values of one of these forms: "x,y": Offset the stipple patterns by this x and y value relative to the top-level window or to the canvas's origin. "#x,y": For objects on a canvas, use offset x and y relative to the top-level window. "ne", "se", "sw", "nw": Align a corner of the stipple pattern with the corresponding corner of the containing object. For example, "ne" means that the top left corner of the stipple pattern coincides with the top left corner of the area to be stippled. "n", "e", "s", "w": Align the stipple pattern with the center of one side of the containing object. For example, "e" means the center of the stipple pattern will coincide with the center of the right side of the area to be stippled. "center": Align the center of the stipple pattern with the center of the containing object.
Tkinter reference
17
cursor default
Selects the cursor to be shown when the mouse is over the button. NORMAL is the default; use DISABLED if the button is to be initially disabled (grayed out, unresponsive to mouse clicks). Normal foreground (text) color. Text font to be used for the button's label. Height of the button in text lines (for textual buttons) or pixels (for images). The color of the focus highlight when the widget has focus. Image to be displayed on the button (instead of text). How to show multiple text lines: LEFT to left-justify each line; CENTER to center them; or RIGHT to right-justify. The relief style to be used while the mouse is on the button; default relief is RAISED. See Section 5.6, Relief styles (p. 12). Additional padding left and right of the text. See Section 5.1, Dimensions (p. 9) for the possible values for padding. Additional padding above and below the text. Specifies the relief type for the button (see Section 5.6, Relief styles (p. 12)). The default relief is RAISED. See repeatinterval, below. Normally, a button fires only once when the user releases the mouse button. If you want the button to fire at regular intervals as long as the mouse button is held down, set this option to a number of milliseconds to be used between repeats, and set the repeatdelay to the number of milliseconds to wait before starting to repeat. For example, if you specify repeatdelay=500, repeatinterval=100 the button will fire after half a second, and every tenth of a second thereafter, until the user releases the mouse button. If the user does not hold the mouse button down at least repeatdelay milliseconds, the button will fire normally. Set this option to DISABLED to gray out the button and make it unresponsive. Has the value ACTIVE when the mouse is over it. Default is NORMAL. Normally, keyboard focus does visit buttons (see Section 29, Focus: routing keyboard input (p. 106)), and a space character acts as the same as a mouse click, pushing the button. You can set the takefocus option to zero to prevent focus from visiting the button. Text displayed on the button. Use internal newlines to display multiple text lines. An instance of StringVar() that is associated with the text on this button. If the variable is changed, the new value will be displayed on the button. See Section 28, Control variables: the values behind the widgets (p. 104). Default is -1, meaning that no character of the text on the button will be underlined. If nonnegative, the corresponding text character will be underlined. For example, underline=1 would underline the second character of the button's text.
disabledforeground Foreground color used when the button is disabled. fg or foreground font height highlightcolor image justify overrelief padx pady relief repeatdelay repeatinterval
highlightbackground Color of the focus highlight when the widget does not have focus. highlightthickness Thickness of the focus highlight.
state takefocus
text textvariable
underline
18
Tkinter reference
width wraplength
Width of the button in letters (if displaying text) or pixels (if displaying an image). If this value is set to a positive number, the text lines will be wrapped to fit within this length. For possible values, see Section 5.1, Dimensions (p. 9).
Methods on Button objects: .flash() Causes the button to flash several times between active and normal colors. Leaves the button in the state it was in originally. Ignored if the button is disabled. .invoke() Calls the button's callback, and returns what that function returns. Has no effect if the button is disabled or there is no callback.
Tkinter reference
19
highlightbackground Color of the focus highlight when the widget does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness relief scrollregion Color shown in the focus highlight. Thickness of the focus highlight. The relief style of the canvas. Default is FLAT. See Section 5.6, Relief styles (p. 12). A tuple (w, n, e, s) that defines over how large an area the canvas can be scrolled, where w is the left side, n the top, e the right side, and s the bottom. The background color to use displaying selected items. The width of the border to use around selected items. The foreground color to use displaying selected items. Normally, focus (see Section 29, Focus: routing keyboard input (p. 106)) will cycle through this widget with the tab key only if there are keyboard bindings set for it (see Section 30, Events (p. 107) for an overview of keyboard bindings). If you set this option to 1, focus will always visit this widget. Set it to "" to get the default behavior. Size of the canvas in the X dimension. See Section 5.1, Dimensions (p. 9). Normally, canvases can be scrolled horizontally to any position. You can get this behavior by setting xscrollincrement to zero. If you set this option to some positive dimension, the canvas can be positioned only on multiples of that distance, and the value will be used for scrolling by scrolling units, such as when the user clicks on the arrows at the ends of a scrollbar. For more information on scrolling units, see Section 21, The Scrollbar widget (p. 69). If the canvas is scrollable, this attribute should be the .set() method of the horizontal scrollbar. Works like xscrollincrement, but governs vertical movement. If the canvas is scrollable, this attribute should be the .set() method of the vertical scrollbar.
width xscrollincrement
20
Tkinter reference
created at the top of the display list (and hence in front of all other objects), but you can re-order the display list.
Tkinter reference
21
.addtag_enclosed ( newTag, x1, y1, x2, y2) Add tag newTag to all objects that occur completely within the rectangle whose top left corner is (x1, y1) and whose bottom right corner is (x2, y2). .addtag_overlapping ( newTag, x1, y1, x2, y2) Like the previous method, but affects all objects that share at least one point with the given rectangle. .addtag_withtag ( newTag, tagOrId ) Adds tag newTag to the object or objects specified by tagOrId. .bbox ( tagOrId=None ) Returns a tuple (x1, y1, x2, y2) describing a rectangle that encloses all the objects specified by tagOrId. If the argument is omitted, returns a rectangle enclosing all objects on the canvas. The top left corner of the rectangle is (x1, y1) and the bottom right corner is (x2, y2). .canvasx ( screenx, gridspacing=None ) Translates a window x coordinate screenx to a canvas coordinate. If gridspacing is supplied, the canvas coordinate is rounded to the nearest multiple of that value. .canvasy ( screeny, gridspacing=None ) Translates a window y coordinate screeny to a canvas coordinate. If gridspacing is supplied, the canvas coordinate is rounded to the nearest multiple of that value. .coords ( tagOrId, x0, y0, x1, y1, ..., xn, yn ) If you pass only the tagOrId argument, returns a tuple of the coordinates of the lowest or only object specified by that argument. The number of coordinates depends on the type of object. In most cases it will be a 4-tuple (x1, y1, x2, y2) describing the bounding box of the object. You can move an object by passing in new coordinates. .dchars ( tagOrId, first=0, last=first ) Deletes characters from a text item or items. Characters between first and last inclusive are deleted, where those values can be integer indices or the string "end" to mean the end of the text. For example, for a canvas C and an item I, C.dchars(I, 1, 1) will remove the second character. .delete ( tagOrId ) Deletes the object or objects selected by tagOrId. It is not considered an error if no items match tagOrId. .dtag ( tagOrId, tagToDelete ) Removes the tag specified by tagToDelete from the object or objects specified by tagOrId. .find_above ( tagOrId ) Returns the ID number of the object just above the object specified by tagOrId. If multiple objects match, you get the highest one. Returns an empty tuple if you pass it the object ID of the highest object. .find_all() Returns a list of the object ID numbers for all objects on the canvas, from lowest to highest. .find_below ( tagOrId ) Returns the object ID of the object just below the one specified by tagOrId. If multiple objects match, you get the lowest one. Returns an empty tuple if you pass it the object ID of the lowest object. .find_closest ( x, y, halo=None, start=None ) Returns a singleton tuple containing the object ID of the object closest to point (x, y). If there are no qualifying objects, returns an empty tuple. Use the halo argument to increase the effective size of the point. For example, halo=5 would treat any object within 5 pixels of (x, y) as overlapping.
22
Tkinter reference
If an object ID is passed as the start argument, this method returns the highest qualifying object that is below start in the display list. .find_enclosed ( x1, y1, x2, y2 ) Returns a list of the object IDs of all objects that occur completely within the rectangle whose top left corner is (x1, y1) and bottom right corner is (x2, y2). .find_overlapping ( x1, y1, x2, y2 ) Like the previous method, but returns a list of the object IDs of all the objects that share at least one point with the given rectangle. .find_withtag ( tagOrId ) Returns a list of the object IDs of the object or objects specified by tagOrId. .focus ( tagOrId=None ) Moves the focus to the object specified by tagOrId. If there are multiple such objects, moves the focus to the first one in the display list that allows an insertion cursor. If there are no qualifying items, or the canvas does not have focus, focus does not move. If the argument is omitted, returns the ID of the object that has focus, or "" if none of them do. .gettags ( tagOrId ) If tagOrId is an object ID, returns a list of all the tags associated with that object. If the argument is a tag, returns all the tags for the lowest object that has that tag. .icursor ( tagOrId, index ) Assuming that the selected item allows text insertion and has the focus, sets the insertion cursor to index, which may be either an integer index or the string "end". Has no effect otherwise. .index ( tagOrId, specifier ) Returns the integer index of the given specifier in the text item specified by tagOrId (the lowest one that, if tagOrId specifies multiple objects). The return value is the corresponding position as an integer, with the usual Python convention, where 0 is the position before the first character. The specifier argument may be any of: INSERT, to return the current position of the insertion cursor. END, to return the position after the last character of the item. SEL_FIRST, to return the position of the start of the current text selection. Tkinter will raise a TclError exception if the text item does not currently contain the text selection. SEL_LAST, to return the position after the end of the current text selection, or raise TclError if the item does not currently contain the selection. A string of the form @x,y, to return the character of the character containing canvas coordinates (x, y). If those coordinates are above or to the left of the text item, the method returns 0; if the coordinates are to the right of or below the item, the method returns the index of the end of the item. .insert ( tagOrId, specifier, text ) Inserts the given string into the object or objects specified by tagOrId, at the position given by the specifier argument. The specifier values may be: Any of the keywords INSERT, END, SEL_FIRST, or SEL_LAST. Refer to the description of the index method above for the interpretation of these codes. The position of the desired insertion, using the normal Python convention for positions in strings.
Tkinter reference
23
.itemcget ( tagOrId, option ) Returns the value of the given configuration option in the selected object (or the lowest object if tagOrId specifies more than one). This is similar to the .cget() method for Tkinter objects. .itemconfigure ( tagOrId, option, ... ) If no option arguments are supplied, returns a dictionary whose keys are the options of the object specified by tagOrId (the lowest one, if tagOrId specifies multiple objects). To change the configuration option of the specified item, supply one or more keyword arguments of the form option=value. .move ( tagOrId, xAmount, yAmount ) Moves the items specified by tagOrId by adding xAmount to their x coordinates and yAmount to their y coordinates. .postscript ( option, ... ) Generates an Encapsulated PostScript representation of the canvas's current contents. The options include: colormode Use "color" for color output, "gray" for grayscale, or "mono" for black and white. file height rotate x y width If supplied, names a file where the PostScript will be written. If this option is not given, the PostScript is returned as a string. How much of the Y size of the canvas to print. Default is all. If false, the page will be rendered in portrait orientation; if true, in landscape. Leftmost canvas coordinate of the area to print. Topmost canvas coordinate of the area to print. How much of the X size of the canvas to print. Default is all.
.scale ( tagOrId, xOffset, yOffset, xScale, yScale ) Scale all objects according to their distance from a point P=(xOffset, yOffset). The scale factors xScale and yScale are based on a value of 1.0, which means no scaling. Every point in the objects selected by tagOrId is moved so that its x distance from P is multiplied by xScale and its y distance is multiplied by yScale. This method will not change the size of a text item, but may move it. .scan_dragto ( x, y, gain=10.0 ) See the .scan_mark() method below. .scan_mark ( x, y ) This method is used to implement fast scrolling of a canvas. The intent is that the user will press and hold a mouse button, then move the mouse up to scan (scroll) the canvas horizontally and vertically in that direction at a rate that depends on how far the mouse has moved since the mouse button was depressed. To implement this feature, bind the mouse's button-down event to a handler that calls scan_mark(x, y) where x and y are the current mouse coordinates. Bind the <Motion> event to a handler that, assuming the mouse button is still down, calls scan_dragto(x, y, gain) where x and y are the current mouse coordinates. The gain argument controls the rate of scanning. This argument has a default value of 10.0. Use larger numbers for faster scanning.
24
Tkinter reference
.select_adjust ( oid, specifier ) Adjusts the boundaries of the current text selection to include the position given by the specifier argument, in the text item with the object ID oid. The current selection anchor is also set to the specified position. For a discussion of the selection anchor, see the canvas select_from method below. For the values of specifier, see the canvas insert method above. .select_clear() Removes the current text selection, if it is set. If there is no current selection, does nothing. .select_from ( oid, specifier ) This method sets the selection anchor to the position given by the specifier argument, within the text item whose object ID is given by oid. The currently selected text on a given canvas is specified by three positions: the start position, the end position, and the selection anchor, which may be anywhere within those two positions. To change the position of the currently selected text, use this method in combination with the select_adjust, select_from, and select_to canvas methods (q.v.). .select_item() If there is a current text selection on this canvas, return the object ID of the text item containing the selection. If there is no current selection, this method returns None. .select_to ( oid, specifier This method changes the current text selection so that it includes the select anchor and the position given by specifier within the text item whose object ID is given by oid. For the values of specifier, see the canvas insert method above. .tag_bind ( tagOrId, sequence=None, function=None, add=None ) Binds events to objects on the canvas. For the object or objects selected by tagOrId, associates the handler function with the event sequence. If the add argument is a string starting with "+", the new binding is added to existing bindings for the given sequence, otherwise the new binding replaces that for the given sequence. For general information on event bindings, see Section 30, Events (p. 107). Note that the bindings are applied to items that have this tag at the time of the tag_bind method call. If tags are later removed from those items, the bindings will persist on those items. If the tag you specify is later applied to items that did not have that tag when you called tag_bind, that binding will not be applied to the newly tagged items. .tag_lower ( tagOrId, belowThis ) Moves the object or objects selected by tagOrId within the display list to a position just below the first or only object specied by the tag or ID belowThis. If there are multiple items with tag tagOrId, their relative stacking order is preserved. This method does not affect canvas window items. To change a window item's stacking order, use a lower or lift method on the window. .tag_raise ( tagOrId, aboveThis ) Moves the object or objects selected by tagOrId within the display list to a position just above the first or only object specied by the tag or ID aboveThis. If there are multiple items with tag tagOrId, their relative stacking order is preserved. This method does not affect canvas window items. To change a window item's stacking order, use a lower or lift method on the window.
Tkinter reference
25
.tag_unbind ( tagOrId, sequence, funcId=None ) Removes bindings for handler funcId and event sequence from the canvas object or objects specified by tagOrId. See Section 30, Events (p. 107). .type ( tagOrId ) Returns the type of the first or only object specified by tagOrId. The return value will be one of the strings "arc", "bitmap", "image", "line", "oval", "polygon", "rectangle", "text", or "window". .xview ( MOVETO, fraction ) This method scrolls the canvas relative to its image, and is intended for binding to the command option of a related scrollbar. The canvas is scrolled horizontally to a position given by offset, where 0.0 moves the canvas to its leftmost position and 1.0 to its rightmost position. .xview ( SCROLL, n, what ) This method moves the canvas left or right: the what argument specifies how much to move and can be either UNITS or PAGES, and n tells how many units to move the canvas to the right relative to its image (or left, if negative). The size of the move for UNITS is given by the value of the canvas's xscrollincrement option; see Section 21, The Scrollbar widget (p. 69). For movements by PAGES, n is multiplied by nine-tenths of the width of the canvas. .xview_moveto ( fraction ) This method scrolls the canvas in the same way as .xview(MOVETO, fraction). .xview_scroll ( n, what ) Same as .xview(SCROLL, n, what). .yview ( MOVETO, fraction ) The vertical scrolling equivalent of .xview(MOVETO,). .yview ( SCROLL, n, what ) The vertical scrolling equivalent of .xview(SCROLL,). .yview_moveto ( fraction ) The vertical scrolling equivalent of .xview(). .yview_scroll ( n, what ) The vertical scrolling equivalents of .xview(), .xview_moveto(), and .xview_scroll().
26
Tkinter reference
activedash activefill activeoutline activeoutlinestipple activestipple activewidth dash dashoffset disableddash disabledfill disabledoutline disabledoutlinestipple disabledstipple disabledwidth extent fill
These options apply when the arc is in the ACTIVE state, that is, when the mouse is over the arc. For example, the activefill option specifies the interior color when the arc is active. For option values, see dash, fill, outline, outlinestipple, stipple, and width, respectively.
Dash pattern for the outline. See Section 5.13, Dash patterns (p. 16). Dash pattern offset for the outline. See Section 5.13, Dash patterns (p. 16). These options apply when the arc's state is DISABLED.
Width of the slice in degrees. The slice starts at the angle given by the start option and extends counterclockwise for extent degrees. By default, the interior of an arc is transparent, and fill="" will select this behavior. You can also set this option to any color and the interior of the arc will be filled with that color. Stipple pattern offset for the interior of the arc. See Section 5.14, Matching stipple patterns (p. 16). The color of the border around the outside of the slice. Default is black. Stipple pattern offset for the outline. See Section 5.14, Matching stipple patterns (p. 16). If the outline option is used, this option specifies a bitmap used to stipple the border. Default is black, and that default can be specified by setting outlinestipple="". Starting angle for the slice, in degrees, measured from +x direction. If omitted, you get the entire ellipse. This option is NORMAL by default. It may be set to HIDDEN to make the arc invisible or to DISABLED to gray out the arc and make it unresponsive to events. A bitmap indicating how the interior fill of the arc will be stippled. Default is stipple="" (solid). You'll probably want something like stipple="gray25". Has no effect unless fill has been set to some color. The default is to draw the whole arc; use style=PIESLICE for this style. To draw only the circular arc at the edge of the slice, use style=ARC. To draw the circular arc and the chord (a straight line connecting the endpoints of the arc), use style=CHORD.
start state
stipple
style
Tkinter reference
27
PIESLICE
CHORD
ARC
tags width
If a single string, the arc is tagged with that string. Use a tuple of strings to tag the arc with multiple tags. See Section 7.4, Canvas tags (p. 21). Width of the border around the outside of the arc. Default is 1 pixel.
background bitmap
disabledbackground These options specify the background, bitmap, and foreground to be used when the bitmap's state is DISABLED. disabledbitmap disabledforeground foreground state The color that will appear where there are 1 values in the bitmap. The default is foreground="black". By default, items are created with state=NORMAL. Use DISABLED to make the item grayed out and unresponsive to events; use HIDDEN to make the item invisible. The tag or tags to be associated with the object, as a string or tuple of strings. See Section 7.4, Canvas tags (p. 21).
tags
28
Tkinter reference
disabledimage Image to be displayed when the item is inactive. For option values, see image below. image state The image to be displayed. See Section 5.9, Images (p. 14), above, for information about how to create images that can be loaded onto canvases. Normally, image objects are created in state NORMAL. Set this value to DISABLED to make it grayed-out and unresponsive to the mouse. If you set it to HIDDEN, the item is invisible. The tags to be associated with the object, as a sequence of strings. See Section 7.4, Canvas tags (p. 21).
tags
Tkinter reference
29
arrowshape
A tuple (d1, d2, d3) that describes the shape of the arrowheads added by the arrow option. Default is (8,10,3).
d2
d3
d1
You can specify the shape of the ends of the line with this option; see Section 5.12, Cap and join styles (p. 15). The default option is BUTT. To produce a dashed line, specify this option; see Section 5.13, Dash patterns (p. 16). The default appearance is a solid line. If you specify a dash pattern, the default is to start the specified pattern at the beginning of the line. The dashoffset option allows you to specify that the start of the dash pattern occurs at a given distance after the start of the line. See Section 5.13, Dash patterns (p. 16). The dash, fill, stipple, and width values to be used when the item is in the DISABLED state.
The color to use in drawing the line. Default is fill="black". For lines that are made up of more than one line segment, this option controls the appearance of the junction between segments. For more details, see Section 5.12, Cap and join styles (p. 15). The default style is ROUND For stippled lines, the purpose of this option is to match the item's stippling pattern with those of adjacent objects. See Section 5.14, Matching stipple patterns (p. 16).. If true, the line is drawn as a series of parabolic splines fitting the point set. Default is false, which renders the line as a set of straight segments. If the smooth option is true, each spline is rendered as a number of straight line segments. The splinesteps option specifies the number of segments used to approximate each section of the line; the default is splinesteps=12. Normally, line items are created in state NORMAL. Set this option to HIDDEN to make the line invisible; set it to DISABLED to make it unresponsive to the mouse. To draw a stippled line, set this option to a bitmap that specifies the stippling pattern, such as stipple="gray25". See Section 5.7, Bitmaps (p. 12) for the possible values. The tags to be associated with the object, as a sequence of strings. See Section 7.4, Canvas tags (p. 21). The line's width. Default is 1 pixel. See Section 5.1, Dimensions (p. 9) for possible values.
offset
smooth splinesteps
state stipple
tags width
30
Tkinter reference
(x0, y0)
(x1,y1)
The oval will coincide with the top and left-hand lines of this box, but will fit just inside the bottom and right-hand sides. To create an ellipse on a canvas C, use: id = C.create_oval ( x0, y0, x1, y1, option, ... ) which returns the object ID of the new oval object on canvas C. Options for ovals: activedash activefill activeoutline activeoutlinestipple activestipple activewidth dash dashoffset To produce a dashed border around the oval, set this option to a dash pattern; see Section 5.13, Dash patterns (p. 16) When using the dash option, the dashoffset option is used to change the alignment of the border's dash pattern relative to the oval. See Section 5.14, Matching stipple patterns (p. 16). These options specify the appearance of the oval when the item's state is DISABLED. These options specify the dash pattern, fill color, outline color, outline stipple pattern, interior stipple pattern, and outline width values to be used when the oval is in the ACTIVE state, that is, when the mouse is over the oval. For option values, see dash, fill, outline, outlinestipple, stipple, and width.
The default appearance of an oval's interior is transparent, and a value of fill="" will select this behavior. You can also set this option to any color and the interior of the ellipse will be filled with that color; see Section 5.3, Colors (p. 9). Stipple pattern offset of the interior. See Section 5.14, Matching stipple patterns (p. 16).
offset
Tkinter reference
31
The color of the border around the outside of the ellipse. Default is outline="black". Stipple pattern offset of the border. See Section 5.14, Matching stipple patterns (p. 16). A bitmap indicating how the interior of the ellipse will be stippled. Default is stipple="", which means a solid color. A typical value would be stipple="gray25". Has no effect unless the fill has been set to some color. See Section 5.7, Bitmaps (p. 12). Stipple pattern to be used for the border. For option values, see stipple below. By default, oval items are created in state NORMAL. Set this option to DISABLED to make the oval unresponsive to mouse actions. Set it to HIDDEN to make the item invisible. The tags to be associated with the object, as a sequence of strings. See Section 7.4, Canvas tags (p. 21). Width of the border around the outside of the ellipse. Default is 1 pixel; see Section 5.1, Dimensions (p. 9) for possible values. If you set this to zero, the border will not appear. If you set this to zero and make the fill transparent, you can make the entire oval disappear.
outlinestipple state
tags width
(x2,y2)
To create a new polygon object on a canvas C: id = C.create_polygon ( x0, y0, x1, y1, ..., option, ... ) The constructor returns the object ID for that object. Options: activedash activefill activeoutline activeoutlinestipple activestipple These options specify the appearance of the polygon when it is in the ACTIVE state, that is, when the mouse is over it. For option values, see dash, fill, outline, outlinestipple, stipple, and width.
32
Tkinter reference
activewidth dash dashoffset disableddash disabledfill disabledoutline disabledoutlinestipple disabledstipple disabledwidth fill You can color the interior by setting this option to a color. The default appearance for the interior of a polygon is transparent, and you can set fill="" to get this behavior. See Section 5.3, Colors (p. 9). This option controls the appearance of the intersections between adjacent sides of the polygon. See Section 5.12, Cap and join styles (p. 15). Offset of the stipple pattern in the interior of the polygon. See Section 5.14, Matching stipple patterns (p. 16). Color of the outline; defaults to outline="", which makes the outline transparent. Stipple offset for the border. See Section 5.14, Matching stipple patterns (p. 16). Use this option to get a stippled border around the polygon. The option value must be a bitmap; see Section 5.7, Bitmaps (p. 12). The default outline uses straight lines to connect the vertices; use smooth=0 to get that behavior. If you use smooth=1, you get a continuous spline curve. Moreover, if you set smooth=1, you can make any segment straight by duplicating the coordinates at each end of that segment. If the smooth option is true, each spline is rendered as a number of straight line segments. The splinesteps option specifies the number of segments used to approximate each section of the line; the default is splinesteps=12. By default, polygons are created in the NORMAL state. Set this option to HIDDEN to make the polygon invisible, or set it to DISABLED to make it unresponsive to the mouse. A bitmap indicating how the interior of the polygon will be stippled. Default is stipple="", which means a solid color. A typical value would be stipple="gray25". Has no effect unless the fill has been set to some color. See Section 5.7, Bitmaps (p. 12). The tags to be associated with the object, as a sequence of strings. See Section 7.4, Canvas tags (p. 21). Width of the outline; defaults to 1. See Section 5.1, Dimensions (p. 9). Use this option to produce a dashed border around the polygon. See Section 5.13, Dash patterns (p. 16). Use this option to start the dash pattern at some point in its cycle other than the beginning. See Section 5.13, Dash patterns (p. 16). These options specify the appearance of the polygon when its state is DISABLED.
splinesteps
state
stipple
tags width
Tkinter reference
33
34
Tkinter reference
outlinestipple state
Use this option to produce a stippled outline. The pattern is specified by a bitmap; see Section 5.7, Bitmaps (p. 12). By default, rectangles are created in the NORMAL state. The state is ACTIVE when the mouse is over the rectangle. Set this option to DISABLED to gray out the rectangle and make it unresponsive to mouse events. A bitmap indicating how the interior of the rectangle will be stippled. Default is stipple="", which means a solid color. A typical value would be stipple="gray25". Has no effect unless the fill has been set to some color. See Section 5.7, Bitmaps (p. 12). The tags to be associated with the object, as a sequence of strings. See Section 7.4, Canvas tags (p. 21). Width of the border. Default is 1 pixel. Use width=0 to make the border invisible. See Section 5.1, Dimensions (p. 9).
stipple
tags width
disabledfill
disabledstipple The stipple pattern to be used when the text is disabled. For option values, see stipple below. fill font justify offset state The default text color is black, but you can render it in any color by setting the fill option to that color. See Section 5.3, Colors (p. 9). If you don't like the default font, set this option to any font value. See Section 5.4, Type fonts (p. 10). For multi-line textual displays, this option controls how the lines are justified: LEFT (the default), CENTER, or RIGHT. The stipple offset to be used in rendering the text. For more information, see Section 5.14, Matching stipple patterns (p. 16). By default, the text item's state is NORMAL. Set this option to DISABLED to make in unresponsive to mouse events, or set it to HIDDEN to make it invisible.
Tkinter reference
35
stipple
A bitmap indicating how the text will be stippled. Default is stipple="", which means solid. A typical value would be stipple="gray25". See Section 5.7, Bitmaps (p. 12). The tags to be associated with the object, as a sequence of strings. See Section 7.4, Canvas tags (p. 21). The text to be displayed in the object, as a string. Use newline characters ("\n") to force line breaks. If you don't specify a width option, the text will be set inside a rectangle as long as the longest line. However, you can also set the width option to a dimension, and each line of the text will be broken into shorter lines, if necessary, or even broken within words, to fit within the specified width. See Section 5.1, Dimensions (p. 9).
You can change the text displayed in a text item. To retrieve the text from an item with object ID I on a canvas C, call C.itemcget(I, "text"). To replace the text in an item with object ID I on a canvas C with the text from a string S, call C.itemconfigure(I, text=S). A number of canvas methods allow you to manipulate text items. See Section 7.6, Methods on Canvas widgets (p. 21), especially dchars, focus, icursor, index, and insert.
36
Tkinter reference
window Use window=w where w is the widget you want to place onto the canvas. If this is omitted initially, you can later call C.itemconfigure ( id, window=w) to place the widget w onto the canvas, where id is the window's object ID..
The purpose of a checkbutton widget (sometimes called checkbox) is to allow the user to read and select a two-way choice. The graphic above shows how checkbuttons look in the off (0) and on (1) state in one implementation: this is a screen shot of two checkbuttons using 24-point Times font. The indicator is the part of the checkbutton that shows its state, and the label is the text that appears beside it. You will need to create a control variable, an instance of the IntVar class, so your program can query and set the state of the checkbutton. See Section 28, Control variables: the values behind the widgets (p. 104), below. You can also use event bindings to react to user actions on the checkbutton; see Section 30, Events (p. 107), below. You can disable a checkbutton. This changes its appearance to grayed out and makes it unresponsive to the mouse. You can get rid of the checkbutton indicator and make the whole widget a push-push button that looks recessed when it is set, and looks raised when it is cleared. To create a checkbutton in an existing parent window or frame parent: w = Checkbutton ( parent, option, ... ) The constructor returns a new Checkbutton widget. Options include: activebackground activeforeground anchor Background color when the checkbutton is under the cursor. See Section 5.3, Colors (p. 9). Foreground color when the checkbutton is under the cursor. If the widget inhabits a space larger than it needs, this option specifies where the checkbutton will sit in that space. The default is anchor=CENTER. See Section 5.5, Anchors (p. 11) for the allowable values. For example, if you use anchor=NW, the widget will be placed in the upper left corner of the space. The normal background color displayed behind the label and indicator. See Section 5.3, Colors (p. 9). For the bitmap option, this specifies the color displayed for 0-bits in the bitmap. To display a monochrome image on a button, set this option to a bitmap; see Section 5.7, Bitmaps (p. 12). The size of the border around the indicator. Default is two pixels. For possible values, see Section 5.1, Dimensions (p. 9). A procedure to be called every time the user changes the state of this checkbutton.
bg or background
Tkinter reference
37
compound
Use this option to display both text and a graphic, which may be either a bitmap or an image, on the button. Allowable values describe the position of the graphic relative to the text, and may be any of BOTTOM, TOP, LEFT, RIGHT, or CENTER. For example, compound=LEFT would position the graphic to the left of the text. If you set this option to a cursor name (see Section 5.8, Cursors (p. 12)), the mouse cursor will change to that pattern when it is over the checkbutton. The foreground color used to render the text of a disabled checkbutton. The default is a stippled version of the default foreground color. The font used for the text. See Section 5.4, Type fonts (p. 10). The color used to render the text. For the bitmap option, this specifies the color displayed for 1-bits in the bitmap. The number of lines of text on the checkbutton. Default is 1.
highlightbackground The color of the focus highlight when the checkbutton does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness image indicatoron The color of the focus highlight when the checkbutton has the focus. The thickness of the focus highlight. Default is 1. Set to 0 to suppress display of the focus highlight. To display a graphic image on the button, set this option to an image object. See Section 5.9, Images (p. 14). Normally a checkbutton displays as its indicator a box that shows whether the checkbutton is set or not. You can get this behavior by setting indicatoron=1. However, if you set indicatoron=0, the indicator disappears, and the entire widget becomes a push-push button that looks raised when it is cleared and sunken when it is set. You may want to increase the borderwidth value to make it easier to see the state of such a control. If the text contains multiple lines, this option controls how the text is justified: CENTER, LEFT, or RIGHT. By default, checkbuttons use the RAISED relief style when the button is off (cleared); use this option to specify a different relief style to be displayed when the button is off. See Section 5.6, Relief styles (p. 12) for values. Normally, a checkbutton's associated control variable will be set to 0 when it is cleared (off). You can supply an alternate value for the off state by setting offvalue to that value. Normally, a checkbutton's associated control variable will be set to 1 when it is set (on). You can supply an alternate value for the on state by setting onvalue to that value. Use this option to specify a relief style to be displayed when the mouse is over the checkbutton; see Section 5.6, Relief styles (p. 12). How much space to leave to the left and right of the checkbutton and text. Default is 1 pixel. For possible values, see Section 5.1, Dimensions (p. 9). How much space to leave above and below the checkbutton and text. Default is 1 pixel. With the default value, relief=FLAT, the checkbutton does not stand out from its background. You may set this option to any of the other styles (see
justify offrelief
offvalue
onvalue
38
Tkinter reference
Section 5.6, Relief styles (p. 12)), or use relief=SOLID, which gives you a solid black frame around it. selectcolor selectimage state The color of the checkbutton when it is set. Default is selectcolor="red". If you set this option to an image, that image will appear in the checkbutton when it is set. See Section 5.9, Images (p. 14). The default is state=NORMAL, but you can use state=DISABLED to gray out the control and make it unresponsive. If the cursor is currently over the checkbutton, the state is ACTIVE. The default is that the input focus (see Section 29, Focus: routing keyboard input (p. 106)) will pass through a checkbutton. If you set takefocus=0, focus will not pass through it. The label displayed next to the checkbutton. Use newlines ("\n") to display multiple lines of text. If you need to change the label on a checkbutton during execution, create a StringVar (see Section 28, Control variables: the values behind the widgets (p. 104)) to manage the current value, and set this option to that control variable. Whenever the control variable's value changes, the checkbutton's annotation will automatically change as well. With the default value of -1, none of the characters of the text label are underlined. Set this option to the index of a character in the text (counting from zero) to underline that character. The control variable that tracks the current state of the checkbutton; see Section 28, Control variables: the values behind the widgets (p. 104). Normally this variable is an IntVar, and 0 means cleared and 1 means set, but see the offvalue and onvalue options above. The default width of a checkbutton is determined by the size of the displayed image or text. You can set this option to a number of characters and the checkbutton will always have room for that many characters. Normally, lines are not wrapped. You can set this option to a number of characters and all lines will be broken into pieces no longer than that number.
takefocus
text textvariable
underline
variable
width
wraplength
Methods on checkbuttons include: .deselect() Clears (turns off) the checkbutton. .flash() Flashes the checkbutton a few times between its active and normal colors, but leaves it the way it started. .invoke() You can call this method to get the same actions that would occur if the user clicked on the checkbutton to change its state. .select() Sets (turns on) the checkbutton. .toggle() Clears the checkbutton if set, sets it if cleared.
Tkinter reference
39
fg or foreground
40
Tkinter reference
font
The font used for text entered in the widget by the user. See Section 5.4, Type fonts (p. 10).
highlightbackground Color of the focus highlight when the widget does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness insertbackground Color shown in the focus highlight when the widget has the focus. Thickness of the focus highlight. By default, the insertion cursor (which shows the point within the text where new keyboard input will be inserted) is black. To get a different color of insertion cursor, set insertbackground to any color; see Section 5.3, Colors (p. 9). By default, the insertion cursor is a simple rectangle. You can get the cursor with the RAISED relief effect (see Section 5.6, Relief styles (p. 12)) by setting insertborderwidth to the dimension of the 3-d border. If you do, make sure that the insertwidth attribute is at least twice that value. By default, the insertion cursor blinks. You can set insertofftime to a value in milliseconds to specify how much time the insertion cursor spends off. Default is 300. If you use insertofftime=0, the insertion cursor won't blink at all. Similar to insertofftime, this attribute specifies how much time the cursor spends on per blink. Default is 600 (milliseconds). By default, the insertion cursor is 2 pixels wide. You can adjust this by setting insertwidth to any dimension. This option controls how the text is justified when the text doesn't fill the widget's width. The value can be LEFT (the default), CENTER, or RIGHT. The background color to be displayed when the widget's state option is "readonly". Selects three-dimensional shading effects around the text entry. See Section 5.6, Relief styles (p. 12). The default is relief=SUNKEN. The background color to use displaying selected text. See Section 5.3, Colors (p. 9). The width of the border to use around selected text. The default is one pixel. The foreground (text) color of selected text. Normally, the characters that the user types appear in the entry. To make a password entry that echoes each character as an asterisk, set show="*". Use this attribute to disable the Entry widget so that the user can't type anything into it. Use state=DISABLED to disable the widget, state=NORMAL to allow user input again. Your program can also find out whether the cursor is currently over the widget by interrogating this attribute; it will have the value ACTIVE when the mouse is over it. You can also set this option to "disabled", which is like the DISABLED state, but the contents of the widget can still be selected or copied. By default, the focus will tab through entry widgets. Set this option to 0 to take the widget out of the sequence. For a discussion of focus, see Section 29, Focus: routing keyboard input (p. 106). In order to be able to retrieve the current text from your entry widget, you must set this option to an instance of the StringVar class; see Section 28,
insertborderwidth
insertofftime
insertontime insertwidth justify readonlybackground relief selectbackground selectborderwidth selectforeground show state
takefocus
textvariable
Tkinter reference
41
Control variables: the values behind the widgets (p. 104). You can retrieve the text using v.get(), or set it using v.set(), where v is the associated control variable. width The size of the entry in characters. The default is 20. For proportional fonts, the physical length of the widget will be based on the average width of a character times the value of the width option. If you expect that users will often enter more text than the onscreen size of the widget, you can link your entry widget to a scrollbar. Set this option to the .set method of the scrollbar. For more information, see Section 9.1, Scrolling an Entry widget (p. 43).
xscrollcommand
Methods on Entry objects include: .delete ( first, last=None ) Deletes characters from the widget, starting with the one at index first, up to but not including the character at position last. If the second argument is omitted, only the single character at position first is deleted. .get() Returns the entry's current text as a string. .icursor ( index ) Set the insertion cursor just before the character at the given index. .index ( index ) Shift the contents of the entry so that the character at the given index is the leftmost visible character. Has no effect if the text fits entirely within the entry. .insert ( index, s ) Inserts string s before the character at the given index. .scan_dragto ( x ) See the scan_mark method below. .scan_mark ( x ) Use this option to set up fast scanning of the contents of the Entry widget that has a scrollbar that supports horizontal scrolling. To implement this feature, bind the mouse's button-down event to a handler that calls scan_mark(x), where x is the current mouse x position. Then bind the <Motion> event to a handler that calls scan_dragto(x), where x is the current mouse x position. The scan_dragto method scrolls the contents of the Entry widget continuously at a rate proportional to the horizontal distance between the position at the time of the scan_mark call and the current position. .select_adjust ( index ) This method is used to make sure that the selection includes the character at the specified index. If the selection already includes that character, nothing happens. If not, the selection is expanded from its current position (if any) to include position index. .select_clear() Clears the selection. If there isn't currently a selection, has no effect. .select_from ( index ) Sets the ANCHOR index position to the character selected by index, and selects that character. .select_present() If there is a selection, returns true, else returns false.
42
Tkinter reference
.select_range ( start, end ) Sets the selection under program control. Selects the text starting at the start index, up to but not including the character at the end index. The start position must be before the end position. To select all the text in an entry widget e, use e.select_range(0, END). .select_to ( index ) Selects all the text from the ANCHOR position up to but not including the character at the given index. .xview ( index ) Same as .xview(). This method is useful in linking the Entry widget to a horizontal scrollbar. See Section 9.1, Scrolling an Entry widget (p. 43). .xview_moveto ( f ) Positions the text in the entry so that the character at position f, relative to the entire text, is positioned at the left edge of the window. The f argument must be in the range [0,1], where 0 means the left end of the text and 1 the right end. .xview_scroll ( number, what ) Used to scroll the entry horizontally. The what argument must be either UNITS, to scroll by character widths, or PAGES, to scroll by chunks the size of the entry widget. The number is positive to scroll left to right, negative to scroll right to left. For example, for an entry widget e, e.xview_scroll(1, PAGES) would move the text one page to the right, and e.xview_scroll(4, UNITS) would move the text four characters to the left.
Tkinter reference
43
Your application's root window is basically a frame. Each frame has its own grid layout, so the gridding of widgets within each frame works independently. Frame widgets are a valuable tool in making your application modular. You can group a set of related widgets into a compound widget by putting them into a frame. Better yet, you can declare a new class that inherits from Frame, adding your own interface to it. This is a good way to hide the details of interactions within a group of related widgets from the outside world. To create a new frame widget in a root window or frame named parent: w = Frame ( parent, option, ... ) The constructor returns the new Frame widget. Options: bg or background bd or borderwidth cursor height The frame's background color. See Section 5.3, Colors (p. 9). Width of the frame's border. The default is 0 (no border). For permitted values, see Section 5.1, Dimensions (p. 9). The cursor used when the mouse is within the frame widget; see Section 5.8, Cursors (p. 12). The vertical dimension of the new frame. This will be ignored unless you also call .grid_propagate(0) on the frame; see Section 4.2, Other grid management methods (p. 6).
highlightbackground Color of the focus highlight when the frame does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness padx pady relief Color shown in the focus highlight when the frame has the focus. Thickness of the focus highlight. Normally, a Frame fits tightly around its contents. To add N pixels of horizontal space inside the frame, set padx=N. Used to add vertical space inside a frame. See padx above. The default relief for a frame is FLAT, which means the frame will blend in with its surroundings. To put a border around a frame, set its borderwidth to a positive value and set its relief to one of the standard relief types; see Section 5.6, Relief styles (p. 12). Normally, frame widgets are not visited by input focus (see Section 29, Focus: routing keyboard input (p. 106) for an overview of this topic). However, you can set takefocus=1 if you want the frame to receive keyboard input. To handle such input, you will need to create bindings for keyboard events; see Section 30, Events (p. 107) for more on events and bindings. The horizontal dimension of the new frame. See Section 5.1, Dimensions (p. 9). This value be ignored unless you also call .grid_propagate(0) on the frame; see Section 4.2, Other grid management methods (p. 6).
takefocus
width
44
Tkinter reference
w = Label ( parent, option, ... ) The constructor returns the new Label widget. Options include: activebackground activeforeground anchor Background color to be displayed when the mouse is over the widget. Foreground color to be displayed when the mouse is over the widget. This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor=CENTER, which centers the text in the available space. For other values, see Section 5.5, Anchors (p. 11). For example, if you use anchor=NW, the text would be positioned in the upper left-hand corner of the available space. The background color of the label area. See Section 5.3, Colors (p. 9). Set this option equal to a bitmap or image object and the label will display that graphic. See Section 5.7, Bitmaps (p. 12) and Section 5.9, Images (p. 14). Width of the border around the label; see Section 5.1, Dimensions (p. 9). The default value is two pixels. If you would like the Label widget to display both text and a graphic (either a bitmap or an image), the compound option specifies the relative orientation of the graphic relative to the text. Values may be any of LEFT, RIGHT, CENTER, BOTTOM, or TOP. For example, if you specify compound=BOTTOM, the graphic will be displayed below the text. Cursor that appears when the mouse is over this label. See Section 5.8, Cursors (p. 12). The foreground color to be displayed when the widget's state is DISABLED. If you are displaying text in this label (with the text or textvariable option, the font option specifies in what font that text will be displayed. See Section 5.4, Type fonts (p. 10). If you are displaying text or a bitmap in this label, this option specifies the color of the text. If you are displaying a bitmap, this is the color that will appear at the position of the 1-bits in the bitmap. See Section 5.3, Colors (p. 9). Height of the label in lines (not pixels!). If this option is not set, the label will be sized to fit its contents. The color of the focus highlight when the widget has focus. Thickness of the focus highlight. To display a static image in the label widget, set this option to an image object. See Section 5.9, Images (p. 14). Specifies how multiple lines of text will be aligned with respect to each other: LEFT for flush left, CENTER for centered (the default), or RIGHT for right-justified. Extra space added to the left and right of the text within the widget. Default is 1.
bg or background bitmap
bd or borderwidth compound
fg or foreground
height
highlightbackground Color of the focus highlight when the widget does not have focus. highlightcolor highlightthickness image justify
padx
Tkinter reference
45
Extra space added above and below the text within the widget. Default is 1. Specifies the appearance of a decorative border around the label. The default is FLAT; for other values, see Section 5.6, Relief styles (p. 12). By default, an Entry widget is in the NORMAL state. Set this option to DISABLED to make it unresponsive to mouse events. The state will be ACTIVE when the mouse is over the widget. Normally, focus does not cycle through Label widgets; see Section 29, Focus: routing keyboard input (p. 106). If you want this widget to be visited by the focus, set takefocus=1. To display one or more lines of text in a label widget, set this option to a string containing the text. Internal newlines ("\n") will force a line break. To slave the text displayed in a label widget to a control variable of class StringVar, set this option to that variable. SeeSection 28, Control variables: the values behind the widgets (p. 104). You can display an underline (_) below the nth letter of the text, counting from 0, by setting this option to n. The default is underline=-1, which means no underlining. Width of the label in characters (not pixels!). If this option is not set, the label will be sized to fit its contents. You can limit the number of characters in each line by setting this option to the desired number. The default value, 0, means that lines will be broken only at newlines.
takefocus
text textvariable
underline
width wraplength
There are no special methods for label widgets other than the common ones (see Section 25, Universal widget methods (p. 93)).
Here is an example of a LabelFrame widget containing two Button widgets. Note that the label Important controls interrupts the border. This widget illustrates the default GROOVE relief (see Section 5.6, Relief styles (p. 12)) and the default 'nw' label anchor, which positions the label at the left side of the top of the frame.
46
Tkinter reference
To create a new LabelFrame widget inside a root window or frame parent: w = LabelFrame ( parent, option, ... ) This constructor returns the new LabelFrame widget. Options: bg or background bd or borderwidth cursor fg or foreground height The background color to be displayed inside the widget; see Section 5.3, Colors (p. 9). Width of the border drawn around the perimeter of the widget; see Section 5.1, Dimensions (p. 9). The default value is two pixels. Selects the cursor that appears when the mouse is over the widget; see Section 5.8, Cursors (p. 12). Color to be used for the label text. The vertical dimension of the new frame. This will be ignored unless you also call .grid_propagate(0) on the frame; see Section 4.2, Other grid management methods (p. 6). The color of the focus highlight when the widget has focus. Use this option to specify the position of the label on the widget's border. The default position is 'nw', which places the label at the left end of the top border. For the nine possible label positions, refer to this diagram:
highlightbackground Color of the focus highlight when the widget does not have focus. highlightcolor labelanchor highlightthickness Thickness of the focus highlight.
nw wn w ws sw
labelwidget
ne en e es
se
Instead of a text label, you can use any widget as the label by passing that widget as the value of this option. If you supply both labelwidget and text options, the text option is ignored. Use this option to add additional padding inside the left and right sides of the widget's frame. The value is in pixels. Use this option to add additional padding inside the top and bottom of the widget's frame. The value is in pixels. This option controls the appearance of the border around the outside of the widget. The default style is GROOVE; for other values, see Section 5.6, Relief styles (p. 12). Normally, the widget will not receive focus; supply a True value to this option to make the widget part of the focus traversal sequence. For more information, see Section 29, Focus: routing keyboard input (p. 106). Text of the label. The horizontal dimension of the new frame. This will be ignored unless you also call .grid_propagate(0) on the frame; see Section 4.2, Other grid management methods (p. 6).
takefocus
text width
Tkinter reference
47
highlightbackground Color of the focus highlight when the widget does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness listvariable Color shown in the focus highlight when the widget has the focus. Thickness of the focus highlight. A StringVar that is connected to the complete list of values in the listbox (see Section 28, Control variables: the values behind the widgets (p. 104). If you call the .get() method of the listvariable, you will get back a string of the form "('v0', 'v1', ...)", where each vi is the contents of one line of the listbox. To change the entire set of lines in the listbox at once, call .set(s) on the listvariable, where s is a string containing the line values with spaces between them.
48
Tkinter reference
For example, if listCon is a StringVar associated with a listbox's listvariable option, this call would set the listbox to contain three lines: listCon.set("ant bee cicada") This call would return the string "('ant', 'bee', 'cicada')": listCon.get() relief selectbackground selectborderwidth Selects three-dimensional border shading effects. The default is SUNKEN. For other values, see Section 5.6, Relief styles (p. 12). The background color to use displaying selected text. The width of the border to use around selected text. The default is that the selected item is shown in a solid block of color selectbackground; if you increase the selectborderwidth, the entries are moved farther apart and the selected entry shows RAISED relief (see Section 5.6, Relief styles (p. 12)). The foreground color to use displaying selected text. Determines how many items can be selected, and how mouse drags affect the selection: BROWSE: Normally, you can only select one line out of a listbox. If you click on an item and then drag to a different line, the selection will follow the mouse. This is the default. SINGLE: You can only select one line, and you can't drag the mousewherever you click button 1, that line is selected. MULTIPLE: You can select any number of lines at once. Clicking on any line toggles whether or not it is selected. EXTENDED: You can select any adjacent group of lines at once by clicking on the first line and dragging to the last line. state takefocus By default, a listbox is in the NORMAL state. To make the listbox unresponsive to mouse events, set this option to DISABLED. Normally, the focus will tab through listbox widgets. Set this option to 0 to take the widget out of the sequence. See Section 29, Focus: routing keyboard input (p. 106). The width of the widget in characters (not pixels!). The width is based on an average character, so some strings of this length in proportional fonts may not fit. The default is 20. If you want to allow the user to scroll the listbox horizontally, you can link your listbox widget to a horizontal scrollbar. Set this option to the .set method of the scrollbar. See Section 13.1, Scrolling a Listbox widget (p. 52) for more on scrollable listbox widgets. If you want to allow the user to scroll the listbox vertically, you can link your listbox widget to a vertical scrollbar. Set this option to the .set method of the scrollbar. See Section 13.1, Scrolling a Listbox widget (p. 52).
selectforeground selectmode
width
xscrollcommand
yscrollcommand
A special set of index forms is used for many of the methods on listbox objects:
Tkinter reference
49
If you specify an index as an integer, it refers to the line in the listbox with that index, counting from 0. Index END refers to the last line in the listbox. Index ACTIVE refers to the selected line. If the listbox allows multiple selections, it refers to the line that was last selected. An index string of the form "@x,y" refers to the line closest to coordinate (x,y) relative to the widget's upper left corner. Methods on listbox objects include: .activate ( index ) Selects the line specifies by the given index. .bbox ( index ) Returns the bounding box of the line specified by index as a 4-tuple (xoffset, yoffset, width, height), where the upper left pixel of the box is at (xoffset, yoffset) and the width and height are given in pixels. The returned width value includes only the part of the line occupied by text. If the line specified by the index argument is not visible, this method returns None. If it is partially visible, the returned bounding box may extend outside the visible area. .curselection() Returns a tuple containing the line numbers of the selected element or elements, counting from 0. If nothing is selected, returns an empty tuple. .delete ( first, last=None ) Deletes the lines whose indices are in the range [first, last], inclusive (contrary to the usual Python idiom, where deletion stops short of the last index), counting from 0. If the second argument is omitted, the single line with index first is deleted. .get ( first, last=None ) Returns a tuple containing the text of the lines with indices from first to last, inclusive. If the second argument is omitted, returns the text of the line closest to first. .index ( i ) If possible, positions the visible part of the listbox so that the line containing index i is at the top of the widget. .insert ( index, *elements ) Insert one or more new lines into the listbox before the line specified by index. Use END as the first argument if you want to add new lines to the end of the listbox. .itemcget(index, option) Retrieves one of the option values for a specific line in the listbox. For option values, see itemconfig below. If the given option has not been set for the given line, the returned value will be an empty string. .itemconfig(index, option=value, ...) Change a configuration option for the line specified by index. Option names include: background The background color of the given line. foreground The text color of the given line.
50
Tkinter reference
selectbackground The background color of the given line when it is selected. selectforeground The text color of the given line when it is selected. .nearest ( y ) Return the index of the visible line closest to the y-coordinate y relative to the listbox widget. .scan_dragto(x, y) See scan_mark below. .scan_mark(x, y) Use this method to implement scanningfast steady scrollingof a listbox. To get this feature, bind some mouse button event to a handler that calls scan_mark with the current mouse position. Then bind the <Motion> event to a handler that calls scan_dragto with the current mouse position, and the listbox will be scrolled at a rate proportional to the distance between the position recorded by scan_mark and the current position. .see ( index ) Adjust the position of the listbox so that the line referred to by index is visible. .selection_anchor ( index ) Place the selection anchor on the line selected by the index argument. Once this anchor has been placed, you can refer to it with the special index form ANCHOR. For example, for a listbox named lbox, this sequence would select lines 3, 4, and 5: lbox.selection_anchor(3) lbox.selection_set(ANCHOR,5) .selection_clear ( first, last=None ) Unselects all of the lines between indices first and last, inclusive. If the second argument is omitted, unselects the line with index first. .selection_includes ( index ) Returns 1 if the line with the given index is selected, else returns 0. .selection_set ( first, last=None ) Selects all of the lines between indices first and last, inclusive. If the second argument is omitted, selects the line with index first. .size() Returns the number of lines in the listbox. .xview() To make the listbox horizontally scrollable, set the command option of the associated horizontal scrollbar to this method. See Section 13.1, Scrolling a Listbox widget (p. 52). .xview_moveto ( fraction ) Scroll the listbox so that the leftmost fraction of the width of its longest line is outside the left side of the listbox. Fraction is in the range [0,1]. .xview_scroll ( number, what ) Scrolls the listbox horizontally. For the what argument, use either UNITS to scroll by characters, or PAGES to scroll by pages, that is, by the width of the listbox. The number argument tells how many to scroll; negative values move the text to the right within the listbox, positive values leftward.
Tkinter reference
51
.yview() To make the listbox vertically scrollable, set the command option of the associated vertical scrollbar to this method. See Section 13.1, Scrolling a Listbox widget (p. 52). .yview_moveto ( fraction ) Scroll the listbox so that the top fraction of the width of its longest line is outside the left side of the listbox. Fraction is in the range [0,1]. .yview_scroll ( number, what ) Scrolls the listbox vertically. For the what argument, use either UNITS to scroll by lines, or PAGES to scroll by pages, that is, by the height of the listbox. The number argument tells how many to scroll; negative values move the text downward inside the listbox, and positive values move the text up.
52
Tkinter reference
A cascade: a text string or image that the user can select to show another whole menu of choices. A checkbutton (see Section 8, The Checkbutton widget (p. 37)). A group of radiobuttons (see Section 19, The Radiobutton widget (p. 63)). To create a menu widget, you must first have created a Menubutton, which we will call mb: w = Menu ( mb, option, ... ) This constructor returns the new Menu widget. Options include: activebackground activeborderwidth The background color that will appear on a choice when it is under the mouse. See Section 5.3, Colors (p. 9). Specifies the width of a border drawn around a choice when it is under the mouse. Default is 1 pixel. For possible values, see Section 5.1, Dimensions (p. 9). The foreground color that will appear on a choice when it is under the mouse. The background color for choices not under the mouse. The width of the border around all the choices; see Section 5.1, Dimensions (p. 9). The default is one pixel. The cursor that appears when the mouse is over the choices, but only when the menu has been torn off. See Section 5.8, Cursors (p. 12). The default font for textual choices. See Section 5.4, Type fonts (p. 10). The foreground color used for choices not under the mouse. You can set this option to a procedure, and that procedure will be called every time someone brings up this menu. The default 3-D effect for menus is relief=RAISED. For other options, see Section 5.6, Relief styles (p. 12). Specifies the color displayed in checkbuttons and radiobuttons when they are selected. Normally, a menu can be torn off: the first position (position 0) in the list of choices is occupied by the tear-off element, and the additional choices are added starting at position 1. If you set tearoff=0, the menu will not have a tear-off feature, and choices will be added starting at position 0. If you would like your program to be notified when the user clicks on the tear-off entry in a menu, set this option to your procedure. It will be called with two arguments: the window ID of the parent window, and the window ID of the new tear-off menu's root window. Normally, the title of a tear-off menu window will be the same as the text of the menubutton or cascade that lead to this menu. If you want to change the title of that window, set the title option to that string.
disabledforeground The color of the text for items whose state is DISABLED. font fg or foreground postcommand relief selectcolor tearoff
tearoffcommand
title
These methods are available on Menu objects. The ones that create choices on the menu have their own particular options; see Section 14.1, Menu item creation (coption) options (p. 55). .add ( kind, coption, ...) Add a new element of the given kind as the next available choice in this menu. The kind argument may be any of "cascade", "checkbutton", "command", "radiobutton", or "separator".
Tkinter reference
53
Depending on the kind argument, this method is equivalent to .add_cascade(), .add_checkbutton(), and so on; refer to those methods below for details. .add_cascade ( coption, ... ) Add a new cascade element as the next available choice in this menu. Use the menu option in this call to connect the cascade to the next level's menu, an object of type Menu. .add_checkbutton ( coption, ... ) Add a new checkbutton as the next available choice in self. The options allow you to set up the checkbutton much the same way as you would set up a Checkbutton object; see Section 14.1, Menu item creation (coption) options (p. 55). .add_command ( coption, ... ) Add a new command as the next available choice in self. Use the label, bitmap, or image option to place text or an image on the menu; use the command option to connect this choice to a procedure that will be called when this choice is picked. .add_radiobutton ( coption, ... ) Add a new radiobutton as the next available choice in self. The options allow you to set up the radiobutton in much the same way as you would set up a Radiobutton object; see Section 19, The Radiobutton widget (p. 63). .add_separator() Add a separator after the last currently defined option. This is just a ruled horizontal line you can use to set off groups of choices. Separators are counted as choices, so if you already have three choices, and you add a separator, the separator will occupy position 3 (counting from 0). .delete ( index1, index2=None ) This method deletes the choices numbered from index1 through index2, inclusive. To delete one choice, omit the index2 argument. You can't use this method to delete a tear-off choice, but you can do that by setting the menu object's tearoff option to 0. .entrycget ( index, coption ) To retrieve the current value of some coption for a choice, call this method with index set to the index of that choice and coption set to the name of the desired option. .entryconfigure ( index, coption, ... ) To change the current value of some coption for a choice, call this method with index set to the index of that choice and one or more coption=value arguments. .index ( i ) Returns the position of the choice specified by index i. For example, you can use .index(END) to find the index of the last choice (or None if there are no choices). .insert_cascade ( index, coption, ... ) Inserts a new cascade at the position given by index, counting from 0. Any choices after that position move down one. The options are the same as for .add_cascade(), above. .insert_checkbutton ( index, coption, ... ) Insert a new checkbutton at the position specified by index. Options are the same as for .add_checkbutton(), above. .insert_command ( index, coption, ... ) Insert a new command at position index. Options are the same as for .add_command(), above. .insert_radiobutton ( index, coption, ... ) Insert a new radiobutton at position index. Options are the same as for .add_radiobutton(), above.
54
Tkinter reference
.insert_separator ( index ) Insert a new separator at the position specified by index. .invoke ( index ) Calls the command callback associated with the choice at position index. If a checkbutton, its state is toggled between set and cleared; if a radiobutton, that choice is set. .post(x, y) Display this menu at position (x, y) relative to the root window. .type ( index ) Returns the type of the choice specified by index: either "cascade", "checkbutton", "command", "radiobutton", "separator", or "tearoff". .yposition ( n ) For the nth menu choice, return the vertical offset in pixels relative to the menu's top. The purpose of this method is to allow you to place a popup menu precisely relative to the current mouse position.
activebackground The background color used for choices when they are under the mouse. activeforeground The foreground color used for choices when they are under the mouse. background bitmap columnbreak The background color used for choices when they are not under the mouse. Note that this cannot be abbreviated as bg. Display a bitmap for this choice; see Section 5.7, Bitmaps (p. 12). Normally all the choices are displayed in one long column. If you set columnbreak=1, this choice will start a new column to the right of the one containing the previous choice. Use option columnbreak=True to start a new column of choices with this choice. A procedure to be called when this choice is activated. If you want to display both text and a graphic (either a bitmap or an image) on a menu choice, use this coption to specify the location of the graphic relative to the text. Values may be any of LEFT, RIGHT, TOP, BOTTOM, CENTER, or NONE. For example, a value of compound=TOP would position the graphic above the text. The font used to render the label text. See Section 5.4, Type fonts (p. 10) The foreground color used for choices when they are not under the mouse. Note that this cannot be abbreviated as fg.
font foreground
Tkinter reference
55
hidemargin
By default, a small margin separates adjacent choices in a menu. Use the coption hidemargin=True to suppress this margin. For example, if your choices are color swatches on a palette, this option will make the swatches touch without any other intervening color. Display an image for this choice; see Section 5.9, Images (p. 14). The text string to appear for this choice. This option is used only for cascade choices. Set it to a Menu object that displays the next level of choices. Normally, the control variable for a checkbutton is set to 0 when the checkbutton is off. You can change the off value by setting this option to the desired value. See Section 28, Control variables: the values behind the widgets (p. 104). Normally, the control variable for a checkbutton is set to 1 when the checkbutton is on. You can change the on value by setting this option to the desired value. Normally, the color displayed in a set checkbutton or radiobutton is red. Change that color by setting this option to the color you want; see Section 5.3, Colors (p. 9). If you are using the image option to display a graphic instead of text on a menu radiobutton or checkbutton, if you use selectimage=I, image I will be displayed when the item is selected. Normally, all choices react to mouse clicks, but you can set state=DISABLED to gray it out and make it unresponsive. This coption will be ACTIVE when the mouse is over the choice. Normally none of the letters in the label are underlined. Set this option to the index of a letter to underline that letter. Specifies the value of the associated control variable (see Section 28, Control variables: the values behind the widgets (p. 104)) for a radiobutton. This can be an integer if the control variable is an IntVar, or a string if the control variable is a StringVar. For checkbuttons or radiobuttons, this option should be set to the control variable associated with the checkbutton or group of radiobuttons. See Section 28, Control variables: the values behind the widgets (p. 104).
onvalue selectcolor
selectimage
state
underline value
variable
56
Tkinter reference
anchor
This options controls where the text is positioned if the widget has more space than the text needs. The default is anchor=CENTER, which centers the text. For other options, see Section 5.5, Anchors (p. 11). For example, if you use anchor=W, the text would be centered against the left side of the widget. The background color when the mouse is not over the menubutton. To display a bitmap on the menubutton, set this option to a bitmap name; see Section 5.7, Bitmaps (p. 12). Width of the border around the menubutton. Default is two pixels. For possible values, see Section 5.1, Dimensions (p. 9). If you specify both text and a graphic (either a bitmap or an image), this option specifies where the graphic appears relative to the text. Possible values are NONE (the default value), TOP, BOTTOM, LEFT, RIGHT, and CENTER. For example, compound=RIGHT would position the graphic to the right of the text. If you specify compound=NONE, the graphic is displayed but the text (if any) is not. The cursor that appears when the mouse is over this menubutton. See Section 5.8, Cursors (p. 12). Normally, the menu will appear below the menubutton. Set direction=LEFT to display the menu to the left of the button; use direction=RIGHT to display the menu to the right of the button; or use direction='above' to place the menu above the button. The foreground color shown on this menubutton when it is disabled. The foreground color when the mouse is not over the menubutton. Specifies the font used to display the text; see Section 5.4, Type fonts (p. 10). The height of the menubutton in lines of text (not pixels!). The default is to fit the menubutton's size to its contents.
cursor direction
highlightbackground Color of the focus highlight when the widget does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness image justify Color shown in the focus highlight when the widget has the focus. Thickness of the focus highlight. To display an image on this menubutton, set this option to the image object. See Section 5.9, Images (p. 14). This option controls where the text is located when the text doesn't fill the menubutton: use justify=LEFT to left-justify the text (this is the default); use justify=CENTER to center it, or justify=RIGHT to right-justify. To associate the menubutton with a set of choices, set this option to the Menu object containing those choices. That menu object must have been created by passing the associated menubutton to the constructor as its first argument. See below for an example showing how to associate a menubutton and menu. How much space to leave to the left and right of the text of the menubutton. Default is 1. How much space to leave above and below the text of the menubutton. Default is 1.
menu
padx pady
Tkinter reference
57
Normally, menubuttons will have RAISED appearance. For other 3-d effects, see Section 5.6, Relief styles (p. 12). Normally, menubuttons respond to the mouse. Set state=DISABLED to gray out the menubutton and make it unresponsive. Normally, menubuttons do not take keyboard focus (see Section 29, Focus: routing keyboard input (p. 106)). Use takefocus=True to add the menubutton to the focus traversal order. To display text on the menubutton, set this option to the string containing the desired text. Newlines ("\n") within the string will cause line breaks. You can associate a control variable of class StringVar with this menubutton. Setting that control variable will change the displayed text. See Section 28, Control variables: the values behind the widgets (p. 104). Normally, no underline appears under the text on the menubutton. To underline one of the characters, set this option to the index of that character. Width of the menubutton in characters (not pixels!). If this option is not set, the label will be sized to fit its contents. Normally, lines are not wrapped. You can set this option to a number of characters and all lines will be broken into pieces no longer than that number.
text textvariable
Here is a brief example showing the creation of a menubutton and its associated menu with two checkboxes: self.mb Menubutton ( self, text="condiments", relief=RAISED ) self.mb.grid() self.mb.menu = self.mb["menu"] Menu ( self.mb, tearoff=0 ) = self.mb.menu =
self.mayoVar = IntVar() self.ketchVar = IntVar() self.mb.menu.add_checkbutton ( label="mayo", variable=self.mayoVar ) self.mb.menu.add_checkbutton ( label="ketchup", variable=self.ketchVar ) This example creates a menubutton labeled condiments. When clicked, two checkbuttons labeled mayo and ketchup will drop down.
58
Tkinter reference
aspect
Use this option to specify the ratio of width to height as a percentage. For example, aspect=100 would give you a text message fit into a square; with aspect=200, the text area would be twice as wide as high. The default value is 150, that is, the text will be fit into a box 50% wider than it is high. The background color behind the text; see Section 5.3, Colors (p. 9). Width of the border around the widget; see Section 5.1, Dimensions (p. 9). The default is two pixels. This option is visible only when the relief option is not FLAT. Specifies the cursor that appears when the mouse is over the widget; see Section 5.8, Cursors (p. 12). Specifies the font used to display the text in the widget; see Section 5.4, Type fonts (p. 10). Specifies the text color; see Section 5.3, Colors (p. 9).
bg or background bd or borderwidth
highlightbackground Color of the focus highlight when the widget does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness justify Color shown in the focus highlight when the widget has the focus. Thickness of the focus highlight. Use this option to specify how multiple lines of text are aligned. Use justify=LEFT to get a straight left margin; justify=CENTER to center each line; and justify=RIGHT to get a straight right margin. Use this option to add extra space inside the widget to the left and right of the text. The value is in pixels. Use this option to add extra space inside the widget above and below the text. The value is in pixels. This option specifies the appearance of the border around the outside of the widget; see Section 5.6, Relief styles (p. 12). The default style is FLAT. Normally, a Message widget will not acquire focus (see Section 29, Focus: routing keyboard input (p. 106)). Use takefocus=True to add the widget to the focus traversal list. The value of this option is the text to be displayed inside the widget. If you would like to be able to change the message under program control, associate this option with a StringVar instance (see Section 28, Control variables: the values behind the widgets (p. 104)). The value of this variable is the text to be displayed. If you specify both text and textvariable options, the text option is ignored. Use this option to specify the width of the text area in the widget, in pixels. The default width depends on the displayed text and the value of the aspect option.
text textvariable
width
Tkinter reference
59
The illustrations above shows an OptionMenu in two states. The left-hand example shows the widget in its initial form. The right-hand example shows how it looks when the mouse has clicked on it and dragged down to the "boat" choice. To create a new OptionMenu widget as the child of a root window or frame named parent: w = OptionMenu ( parent, variable, choice1, choice2, ... ) This constructor returns the new OptionMenu widget. The variable is a StringVar instance (see Section 28, Control variables: the values behind the widgets (p. 104)) that is associated with the widget, and the remaining arguments are the choices to be displayed in the widget as strings. The illustration above was created with this code snippet: optionList = ("train", "plane", "boat") self.v = StringVar() self.v.set(optionList[0]) self.om = OptionMenu ( self, self.v, *optionList ) To find out which choice is currently selected in an OptionMenu widget, the .get() method on the associated control variable will return that choice as a string.
60
Tkinter reference
You may choose to display handles within the widget. A handle is a small square that the user can drag with the mouse. You may choose to make sashes visible. A sash is a bar placed between the child widgets. A pane is the area occupied by one child widget. To create a new PanedWindow widget as the child of a root window or frame named parent: w = PanedWindow ( parent, option, ... ) This constructor returns the new PanedWindow widget. Here are the options: bg or background The background color displayed behind the child widgets; see Section 5.3, Colors (p. 9).
bd or borderwidth Width of the border around the outside of the widget; see Section 5.1, Dimensions (p. 9). The default is two pixels. cursor handlepad The cursor to be displayed when the mouse is over the widget; see Section 5.8, Cursors (p. 12). Use this option to specify the distance between the handle and the end of the sash. For orient=VERTICAL, this is the distance between the left end of the sash and the handle; for orient=HORIZONTAL, it is the distance between the top of the sash and the handle. The default value is eight pixels; for other values, see Section 5.1, Dimensions (p. 9). Use this option to specify the size of the handle, which is always a square; see Section 5.1, Dimensions (p. 9). The default value is eight pixels. Specifies the height of the widget; see Section 5.1, Dimensions (p. 9). If you don't specify this option, the height is determined by the height of the child widgets. This option controls how a resizing operation works. For the default value, opaqueresize=True, the resizing is done continuously as the sash is dragged. If this option is set to False, the sash (and adjacent child widgets) stays put until the user releases the mouse button, and then it jumps to the new position. To stack child widgets horizontally, use orient=HORIZONTAL. To stack them vertically, use orient=VERTICAL.
handlesize height
opaqueresize
orient
Tkinter reference
61
Selects the relief style of the border around the widget; see Section 5.6, Relief styles (p. 12). The default is FLAT. Use this option to allocate extra space on either side of each sash. The default is zero; for other values, see Section 5.1, Dimensions (p. 9). This option specifies the relief style used to render the sashes; see Section 5.6, Relief styles (p. 12). The default style is FLAT. Specifies the width of the sash; see Section 5.1, Dimensions (p. 9). The default width is two pixels. Use showhandle=True to display the handles. For the default value, False, the user can still use the mouse to move the sashes. The handle is simply a visual cue. Width of the widget; see Section 5.1, Dimensions (p. 9). If you don't specify a value, the width will be determined by the sizes of the child widgets.
width
To add child widgets to a PanedWindow, create the child widgets as children of the parent PanedWindow, but rather than using the .grid() method to register them, use the .add() method on the PanedWindow. Here are the methods on PanedWindow widgets. .add ( child[, option=value] ... ) Use this method to add the given child widget as the next child of this PanedWindow. First create the child widget with the PanedWindow as its parent widget, but do not call the .grid() method to register it. Then call .add(child) and the child will appear inside the PanedWindow in the next available position. Associated with each child is a set of configuration options that control its position and appearance. See Section 18.1, PanedWindow child configuration options (p. 63). You can supply these configuration options as keyword arguments to the .add() method. You can also set or change their values anytime with the .paneconfig() method, or retrieve the current value of any of these options using the .panecget() method; these methods are described below. .forget ( child ) Removes a child widget. .identify ( x, y For a given location (x, y) in window coordinates, this method returns a value that describes the feature at that location. If the feature is a child window, the method returns an empty string. If the feature is a sash, the method returns a tuple (n, 'sash') where n is 0 for the first sash, 1 for the second, and so on. If the feature is a handle, the method returns a tuple (n, 'handle') where n is 0 for the first handle, 1 for the second, and so on. .panecget ( child, option This method retrieves the value of a child widget configuration option, where child is the child widget and option is the name of the option as a string. For the list of child widget configuration options, see Section 18.1, PanedWindow child configuration options (p. 63). .paneconfig ( child, option=value, ... ) Use this method to configure options for child widgets. The options are described in Section 18.1, PanedWindow child configuration options (p. 63).
62
Tkinter reference
.panes() This method returns a list of the child widgets, in order from left to right (for orient=HORIZONTAL) or top to bottom (for orient-VERTICAL). .remove ( child ) Removes the given child; this is the same action as the .forget() method. .sash_coord ( index ) This method returns the location of a sash. The index argument selects the sash: 0 for the sash between the first two children, 1 for the sash between the second and third child, and so forth. The result is a tuple (x, y) containing the coordinates of the upper left corner of the sash. .sash_place ( index, x, y ) Use this method to reposition the sash selected by index (0 for the first sash, and so on). The x and y coordinates specify the desired new position of the upper left corner of the sash. Tkinter ignores the coordinate orthogonal to the orientation of the widget: use the x value to reposition the sash for orient=HORIZONTAL, and use the y coordinate to move the sash for option orient=VERTICAL.
before height
minsize Use this option to specify a minimum size for the child widget in the direction of the PanedWindow's orientation. For orient=HORIZONTAL, this is the minimum width; for orient=VERTICAL, it is the minimum height. For permissible values, see Section 5.1, Dimensions (p. 9). padx pady sticky The amount of extra space to be added to the left and right of the child widget; see Section 5.1, Dimensions (p. 9). The amount of extra space to be added above and below the child widget; see Section 5.1, Dimensions (p. 9). This option functions like the sticky argument to the .grid() method; see Section 4.1, The .grid() method (p. 5). It specifies how to position a child widget if the pane is larger than the widget. For example, sticky=NW would position the widget in the upper left (northwest) corner of the pane. Desired width of the child widget; see Section 5.1, Dimensions (p. 9).
width
Tkinter reference
63
The indicator is the diamond-shaped part that turns red in the selected item. The label is the text, although you can use an image or bitmap as the label. If you prefer, you can dispense with the indicator. This makes the radiobuttons look like push-push buttons, with the selected entry appearing sunken and the rest appearing raised. To form several radiobuttons into a functional group, create a single control variable (see Section 28, Control variables: the values behind the widgets (p. 104), below), and set the variable option of each radiobutton to that variable. The control variable can be either an IntVar or a StringVar. If two or more radiobuttons share the same control variable, setting any of them will clear the others. Each radiobutton in a group must have a unique value option of the same type as the control variable. For example, a group of three radiobuttons might share an IntVar and have values of 0, 1, and 99. Or you can use a StringVar control variable and give the radiobuttons value options like "too hot", "too cold", and "just right". To create a new radiobutton widget as the child of a root window or frame named parent: w = Radiobutton ( parent, option, ... )
This constructor returns the new Radiobutton widget. Options: activebackground activeforeground anchor The background color when the mouse is over the radiobutton. See Section 5.3, Colors (p. 9). The foreground color when the mouse is over the radiobutton. If the widget inhabits a space larger than it needs, this option specifies where the radiobutton will sit in that space. The default is anchor=CENTER. For other positioning options, see Section 5.5, Anchors (p. 11). For example, if you set anchor=NE, the radiobutton will be placed in the top right corner of the available space. The normal background color behind the indicator and label. To display a monochrome image on a radiobutton, set this option to a bitmap; see Section 5.7, Bitmaps (p. 12). The size of the border around the indicator part itself. Default is two pixels. For possible values, see Section 5.1, Dimensions (p. 9). A procedure to be called every time the user changes the state of this radiobutton. If you specify both text and a graphic (either a bitmap or an image), this option specifies where the graphic appears relative to the text. Possible values are NONE (the default value), TOP, BOTTOM, LEFT, RIGHT, and CENTER. For example, compound=BOTTOM would position the graphic below the text. If you specify compound=NONE, the graphic is displayed but the text (if any) is not. If you set this option to a cursor name (see Section 5.8, Cursors (p. 12)), the mouse cursor will change to that pattern when it is over the radiobutton.
cursor
64
Tkinter reference
The foreground color used to render the text of a disabled radiobutton. The default is a stippled version of the default foreground color. The font used for the text. See Section 5.4, Type fonts (p. 10). The color used to render the text. The number of lines (not pixels) of text on the radiobutton. Default is 1.
highlightbackground The color of the focus highlight when the radiobutton does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness image The color of the focus highlight when the radiobutton has the focus. The thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress display of the focus highlight. To display a graphic image instead of text for this radiobutton, set this option to an image object. See Section 5.9, Images (p. 14). The image appears when the radiobutton is not selected; compare selectimage, below. Normally a radiobutton displays its indicator. If you set this option to zero, the indicator disappears, and the entire widget becomes a push-push button that looks raised when it is cleared and sunken when it is set. You may want to increase the borderwidth value to make it easier to see the state of such a control. If the text contains multiple lines, this option controls how the text is justified: CENTER (the default), LEFT, or RIGHT. If you suppress the indicator by asserting indicatoron=False, the offrelief option specifies the relief style to be displayed when the radiobutton is not selected. The default values is RAISED. Specifies the relief style to be displayed when the mouse is over the radiobutton. How much space to leave to the left and right of the radiobutton and text. Default is 1. How much space to leave above and below the radiobutton and text. Default is 1. By default, a radiobutton will have FLAT relief, so it doesn't stand out from its background. See Section 5.6, Relief styles (p. 12) for more 3-d effect options. You can also use relief=SOLID, which displays a solid black frame around the radiobutton. The color of the radiobutton when it is set. Default is red. If you are using the image option to display a graphic instead of text when the radiobutton is cleared, you can set the selectimage option to a different image that will be displayed when the radiobutton is set. See Section 5.9, Images (p. 14). The default is state=NORMAL, but you can set state=DISABLED to gray out the control and make it unresponsive. If the cursor is currently over the radiobutton, the state is ACTIVE. By default, the input focus (see Section 29, Focus: routing keyboard input (p. 106)) will pass through a radiobutton. If you set takefocus=0, focus will not visit this radiobutton. The label displayed next to the radiobutton. Use newlines ("\n") to display multiple lines of text.
indicatoron
justify offrelief
selectcolor selectimage
state
takefocus
text
Tkinter reference
65
textvariable
If you need to change the label on a radiobutton during execution, create a StringVar (see Section 28, Control variables: the values behind the widgets (p. 104)) to manage the current value, and set this option to that control variable. Whenever the control variable's value changes, the radiobutton's annotation will automatically change to that text as well. With the default value of -1, none of the characters of the text label are underlined. Set this option to the index of a character in the text (counting from zero) to underline that character. When a radiobutton is turned on by the user, its control variable is set to its current value option. If the control variable is an IntVar, give each radiobutton in the group a different integer value option. If the control variable is a StringVar, give each radiobutton a different string value option. The control variable that this radiobutton shares with the other radiobuttons in the group; see Section 28, Control variables: the values behind the widgets (p. 104). This can be either an IntVar or a StringVar. The default width of a radiobutton is determined by the size of the displayed image or text. You can set this option to a number of characters (not pixels) and the radiobutton will always have room for that many characters. Normally, lines are not wrapped. You can set this option to a number of characters and all lines will be broken into pieces no longer than that number.
underline
value
variable
width
wraplength
Methods on radiobutton objects include: .deselect() Clears (turns off) the radiobutton. .flash() Flashes the radiobutton a few times between its active and normal colors, but leaves it the way it started. .invoke() You can call this method to get the same actions that would occur if the user clicked on the radiobutton to change its state. .select() Sets (turns on) the radiobutton.
66
Tkinter reference
Each scale displays a slider that the user can drag along a trough to change the value. In the figure, the first slider is currently at -0.38 and the second at 7. You can drag the slider to a new value with mouse button 1. If you click button 1 in the trough, the slider will move one increment in that direction per click. Holding down button 1 in the trough will, after a delay, start to auto-repeat its function. If the scale has keyboard focus, left arrow and up arrow keystrokes will move the slider up (for vertical scales) or left (for horizontal scales). Right arrow and down arrow keystrokes will move the slider down or to the right. To create a new scale widget as the child of a root window or frame named parent: w = Scale ( parent, option, ... ) The constructor returns the new Scale widget. Options: activebackground bg or background bd or borderwidth command The color of the slider when the mouse is over it. See Section 5.3, Colors (p. 9). The background color of the parts of the widget that are outside the trough. Width of the 3-d border around the trough and slider. Default is two pixels. For acceptable values, see Section 5.1, Dimensions (p. 9). A procedure to be called every time the slider is moved. This procedure will be passed one argument, the new scale value. If the slider is moved rapidly, you may not get a callback for every possible position, but you'll certainly get a callback when it settles. The cursor that appears when the mouse is over the scale. See Section 5.8, Cursors (p. 12). The way your program reads the current value shown in a scale widget is through a control variable; see Section 28, Control variables: the values behind the widgets (p. 104). The control variable for a scale can be an IntVar, a DoubleVar (float), or a StringVar. If it is a string variable, the digits option controls how many digits to use when the numeric scale value is converted to a string. The font used for the label and annotations. See Section 5.4, Type fonts (p. 10). The color of the text used for the label and annotations. A float or integer value that defines one end of the scale's range. For vertical scales, this is the top end; for horizontal scales, the left end. The underbar (_) is not a typo: because from is a reserved word in Python, this option is
cursor digits
Tkinter reference
67
spelled from_. The default is 0. See the to option, below, for the other end of the range. highlightbackground The color of the focus highlight when the scale does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness label The color of the focus highlight when the scale has the focus. The thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress display of the focus highlight. You can display a label within the scale widget by setting this option to the label's text. The label appears in the top left corner if the scale is horizontal, or the top right corner if vertical. The default is no label. The length of the scale widget. This is the x dimension if the scale is horizontal, or the y dimension if vertical. The default is 100 pixels. For allowable values, see Section 5.1, Dimensions (p. 9). Set orient=HORIZONTAL if you want the scale to run along the x dimension, or orient=VERTICAL to run parallel to the y-axis. Default is vertical. With the default relief=FLAT, the scale does not stand out from its background. You may also use relief=SOLID to get a solid black frame around the scale, or any of the other relief types described in Section 5.6, Relief styles (p. 12). This option controls how long button 1 has to be held down in the trough before the slider starts moving in that direction repeatedly. Default is repeatdelay=300, and the units are milliseconds. This option controls how often the slider jumps once button 1 has been held down in the trough for at least repeatdelay milliseconds. For example, repeatinterval=100 would jump the slider every 100 milliseconds. Normally, the user will only be able to change the scale in whole units. Set this option to some other value to change the smallest increment of the scale's value. For example, if from_=-1.0 and to=1.0, and you set resolution=0.5, the scale will have 5 possible values: -1.0, -0.5, 0.0, +0.5, and +1.0. All smaller movements will be ignored. Use resolution=-1 to disable any rounding of values. Normally, the current value of the scale is displayed in text form by the slider (above it for horizontal scales, to the left for vertical scales). Set this option to 0 to suppress that label. Normally the slider is 30 pixels along the length of the scale. You can change that length by setting the sliderlength option to your desired length; see Section 5.1, Dimensions (p. 9). By default, the slider is displayed with a RAISED relief style. For other relief styles, set this option to any of the values described in Section 5.6, Relief styles (p. 12). Normally, scale widgets respond to mouse events, and when they have the focus, also keyboard events. Set state=DISABLED to make the widget unresponsive. Normally, the focus will cycle through scale widgets. Set this option to 0 if you don't want this behavior. See Section 29, Focus: routing keyboard input (p. 106).
length
orient relief
repeatdelay
repeatinterval
resolution
showvalue
sliderlength
sliderrelief
state
takefocus
68
Tkinter reference
tickinterval
Normally, no ticks are displayed along the scale. To display periodic scale values, set this option to a number, and ticks will be displayed on multiples of that value. For example, if from_=0.0, to=1.0, and tickinterval=0.25, labels will be displayed along the scale at values 0.0, 0.25, 0.50, 0.75, and 1.00. These labels appear below the scale if horizontal, to its left if vertical. Default is 0, which suppresses display of ticks. A float or integer value that defines one end of the scale's range; the other end is defined by the from_ option, discussed above. The to value can be either greater than or less than the from_ value. For vertical scales, the to value defines the bottom of the scale; for horizontal scales, the right end. The default value is 100. The color of the trough. The control variable for this scale, if any; see Section 28, Control variables: the values behind the widgets (p. 104). Control variables may be from class IntVar, DoubleVar (float), or StringVar. In the latter case, the numerical value will be converted to a string. See the the digits option, above, for more information on this conversion. The width of the trough part of the widget. This is the x dimension for vertical scales and the y dimension if the scale has orient=HORIZONTAL. Default is 15 pixels.
to
troughcolor variable
width
Scale objects have these methods: .coords ( value=None ) Returns the coordinates, relative to the upper left corner of the widget, corresponding to a given value of the scale. For value=None, you get the coordinates of the center of the slider at its current position. To find where the slider would be if the scale's value were set to some value x, use value=x. .get() This method returns the current value of the scale. .identify ( x, y ) Given a pair of coordinates (x, y) relative to the top left corner of the widget, this method returns a string identifying what functional part of the widget is at that location. The return value may be any of these: "slider" The slider.
"trough1" For horizontal scales, to the left of the slider; for vertical scales, above the slider. "trough2" For horizontal scales, to the right of the slider; for vertical scales, below the slider. "" Position (x, y) is not on any of the above parts.
Tkinter reference
69
Scrollbars can be horizontal, like the one shown above, or vertical. A widget that has two scrollable dimensions, such as a canvas or listbox, can have both a horizontal and a vertical scrollbar. The slider, or scroll thumb, is the raised-looking rectangle that shows the current scroll position. The two triangular arrowheads at each end are used for moving the position by small steps. The one on the left or top is called arrow1, and the one on the right or bottom is called arrow2. The trough is the sunken-looking area visible behind the arrowheads and slider. The trough is divided into two areas named trough1 (above or to the left of the slider) and trough2 (below or to the right of the slider). The slider's size and position, relative to the length of the entire widget, show the size and position of the view relative to its total size. For example, if a vertical scrollbar is associated with a listbox, and its slider extends from 50% to 75% of the height of the scrollbar, that means that the visible part of the listbox shows that portion of the overall list starting at the halfway mark and ending at the threequarter mark. In a horizontal scrollbar, clicking B1 (button 1) on the left arrowhead moves the view by a small amount to the left. Clicking B1 on the right arrowhead moves the view by that amount to the right. For a vertical scrollbar, clicking the upward- and downward-pointing arrowheads moves the view small amounts up or down. Refer to the discussion of the associated widget to find out the exact amount that these actions move the view. The user can drag the slider with B1 or B2 (the middle button) to move the view. For a horizontal scrollbar, clicking B1 in the trough to the left of the slider moves the view left by a page, and clicking B1 in the trough to the right of the slider moves the view a page to the right. For a vertical scrollbar, the corresponding actions move the view a page up or down. Clicking B2 anywhere along the trough moves the slider so that its left or top end is at the mouse, or as close to it as possible. The normalized position of the scrollbar refers to a number in the closed interval [0.0, 1.0] that defines the slider's position. For vertical scrollbars, position 0.0 is at the top and 1.0 at the bottom; for horizontal scrollbars, position 0.0 is at the left end and 1.0 at the right. To create a new Scrollbar widget as the child of a root window or frame parent: w = Scrollbar ( parent, option, ... ) The constructor returns the new Scrollbar widget. Options for scrollbars include: activebackground activerelief bg or background bd or borderwidth The color of the slider and arrowheads when the mouse is over them. See Section 5.3, Colors (p. 9). By default, the slider is shown with the RAISED relief style. To display the slider with a different relief style when the mouse is over the slider. The color of the slider and arrowheads when the mouse is not over them. The width of the 3-d borders around the entire perimeter of the trough, and also the width of the 3-d effects on the arrowheads and slider. Default is no border around the trough, and a two-pixel border around the arrowheads and slider. For possible values, see Section 5.1, Dimensions (p. 9).
70
Tkinter reference
command
A procedure to be called whenever the scrollbar is moved. For a discussion of the calling sequence, see Section 21.1, The Scrollbar command callback (p. 72). The cursor that appears when the mouse is over the scrollbar. See Section 5.8, Cursors (p. 12). The width of the borders around the arrowheads and slider. The default is elementborderwidth=-1, which means to use the value of the borderwidth option.
cursor elementborderwidth
highlightbackground The color of the focus highlight when the scrollbar does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness jump The color of the focus highlight when the scrollbar has the focus. The thickness of the focus highlight. Default is 1. Set to 0 to suppress display of the focus highlight. This option controls what happens when a user drags the slider. Normally (jump=0), every small drag of the slider causes the command callback to be called. If you set this option to 1, the callback isn't called until the user releases the mouse button. Set orient=HORIZONTAL for a horizontal scrollbar, orient=VERTICAL for a vertical one (the default orientation). Controls the relief style of the widget; the default style is SUNKEN. This option has no effect in Windows. This option controls how long button 1 has to be held down in the trough before the slider starts moving in that direction repeatedly. Default is repeatdelay=300, and the units are milliseconds. This option controls how often slider movement will repeat when button 1 is held down in the trough. Default is repeatinterval=100, and the units are milliseconds. Normally, you can tab the focus through a scrollbar widget; see Section 29, Focus: routing keyboard input (p. 106). Set takefocus=0 if you don't want this behavior. The default key bindings for scrollbars allow the user to use the and arrow keys to move horizontal scrollbars, and they can use the and keys to move vertical scrollbars. The color of the trough. Width of the scrollbar (its y dimension if horizontal, and its x dimension if vertical). Default is 16. For possible values, see Section 5.1, Dimensions (p. 9).
repeatinterval
takefocus
troughcolor width
Methods on scrollbar objects include: .activate(element=None) If no argument is provided, this method returns one of the strings "arrow1", "arrow2", "slider", or "", depending on where the mouse is. For example, the method returns "slider" if the mouse is on the slider. The empty string is returned if the mouse is not currently on any of these three controls. To highlight one of the controls (using its activerelief relief style and its activebackground color), call this method and pass a string identifying the control you want to highlight, one of "arrow1", "arrow2", or "slider".
Tkinter reference
71
.delta ( dx, dy ) Given a mouse movement of (dx, dy) in pixels, this method returns the float that should be added to the current slider position to achieve that same movement. The value must be in the closed interval [-1.0, 1.0]. .fraction ( x, y ) Given a pixel location (x, y), this method returns the corresponding normalized slider position in the interval [0.0, 1.0] that is closest to that location. .get() Returns two numbers (a, b) describing the current position of the slider. The a value gives the position of the left or top edge of the slider, for horizontal and vertical scrollbars respectively; the b value gives the position of the right or bottom edge. Each value is in the interval [0.0, 1.0] where 0.0 is the leftmost or top position and 1.0 is the rightmost or bottom position. For example, if the slider extends from halfway to three-quarters of the way along the trough, you might get back the tuple (0.5,0.75). .identify ( x, y ) This method returns a string indicating which (if any) of the components of the scrollbar are under the given (x, y) coordinates. The return value is one of "arrow1", "trough1", "slider", "trough2", "arrow2", or the empty string "" if that location is not on any of the scrollbar components. .set ( first, last ) To connect a scrollbar to another widget w, set w's xscrollcommand or yscrollcommand to the scrollbar's .set method. The arguments have the same meaning as the values returned by the .get() method. Please note that moving the scrollbar's slider does not move the corresponding widget.
72
Tkinter reference
These calling sequences match the arguments expected by the .xview() and .yview() methods of canvases, listboxes, and text widgets. The Entry widget does not have an .xview() method. See Section 9.1, Scrolling an Entry widget (p. 43).
On the screen, a Spinbox has an area for displaying the current values, and a pair of arrowheads. The user can click the upward-pointing arrowhead to advance the value to the next higher value in sequence. If the value is already at maximum, you can set up the widget, if you wish, so that the new value will wrap around to the lowest value. The user can click the downward-pointing arrowhead to advance the value to the next lower value in sequence. This arrow may also be configured to wrap around, so that if the current value is the lowest, clicking on the down-arrow will display the highest value.
Tkinter reference
73
The user can also enter values directly, treating the widget as if it were an Entry. The user can move the focus to the widget (see Section 29, Focus: routing keyboard input (p. 106)), either by clicking on it or by using tab or shift-tab, and then edit the displayed value. To create a new Spinbox widget as the child of a root window or frame parent: w = Spinbox ( parent, option, ... ) The constructor returns the new Spinbox widget. Options include: activebackground bg or background bd or borderwidth buttonbackground buttoncursor buttondownrelief buttonup command Background color when the cursor is over the widget; see Section 5.3, Colors (p. 9). Background color of the widget. Width of the border around the widget; see Section 5.1, Dimensions (p. 9). The default value is one pixel. The background color displayed on the arrowheads. The default is gray. The cursor to be displayed when the mouse is over the arrowheads; see Section 5.8, Cursors (p. 12). The relief style for the downward-pointing arrowhead; see Section 5.6, Relief styles (p. 12). The default style is RAISED. The relief style for the upward-pointing arrowhead; see Section 5.6, Relief styles (p. 12). The default style is RAISED. Use this option to specify a function or method to be called whenever the user clicks on one of the arrowheads. Note that the callback is not called when the user edits the value directly as if it were an Entry. Selects the cursor that is displayed when the mouse is over the entry part of the widget; see Section 5.8, Cursors (p. 12). These options select the background and foreground colors displayed when the widget's state is DISABLED. Normally, the text in the entry portion of a Spinbox can be cut and pasted. To prohibit this behavior, set the exportselection option to True. Use this option to select a different typeface for the entry text; see Section 5.4, Type fonts (p. 10). This option selects the color used to display the text in the entry part of the widget, and the color of the arrowheads. Use this option to control the formatting of numeric values in combination with the from_ and to options. For example, format='%10.4f' would display the value as a ten-character field, with four digits after the decimal. Use this option in combination with the to option (described below) to constrain the values to a numeric range. For example, from_=1 and to=9 would allow only values between 1 and 9 inclusive. See also the increment option below.
from_
highlightbackground The color of the focus highlight when the Spinbox does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness The color of the focus highlight when the Spinbox has the focus. The thickness of the focus highlight. Default is 1. Set to 0 to suppress display of the focus highlight.
74
Tkinter reference
increment
When you constrain the values with the from_ and to options, you can use the increment option to specify how much the value increases or decreases when the user clicks on an arrowhead. For example, with options from_=0.0, to=2.0, and increment=0.5, the up-arrowhead will step through values 0.0, 0.5, 1.0, 1.5, and 2.0. Selects the color of the insertion cursor displayed in the entry part of the widget. This option controls the width of the border around the insertion cursor. Normally, the insertion cursor will have no border. If this option is set to a nonzero value, the insertion cursor will be displayed in the RAISED relief style. These two options control the blink cycle of the insertion cursor: the amount of time it spends off and on, respectively, in milliseconds. For example, with options insertofftime=200 and insertontime=400, the cursor would blink off for 0.2 seconds and then on for 0.4 seconds. Use this option to specify the width of the insertion cursor; for possible values, see Section 5.1, Dimensions (p. 9). The default width is two pixels. This option controls the position of the text in the entry part of the widget. Values may be LEFT to left-justify the text; CENTER to center it; or RIGHT to right-justify the text. This option specifies the background color that will be displayed when the widget's state is 'readonly'; see Section 5.3, Colors (p. 9). Use this option to select a relief style for the widget; see Section 5.6, Relief styles (p. 12). The default style is SUNKEN. These options specify the auto-repeat behavior of mouse clicks on the arrowheads; values are in milliseconds. The repeatdelay value specifies how long the mouse button must be held down before it repeats, and repeatinterval specifies how often the function repeats. Default values are 400 and 100 milliseconds, respectively. The background color to use displaying selected items. The width of the border to display around selected items. The foreground color to use displaying selected items. Normally, a Spinbox widget is created in the NORMAL state. Set this option to DISABLED to make the widget unresponsive to mouse or keyboard actions. If you set it to 'readonly', the value in the entry part of the widget cannot be modified with keystrokes, but the value can still be copied to the clipboard, and the widget still responds to clicks on the arrowheads. Normally, the entry part of a Spinbox widget can have focus (see Section 29, Focus: routing keyboard input (p. 106)). To remove the widget from the focus traversal sequence, set takefocus=False. If you want to retrieve the current value of the widget, you can use the .get() method below, or you can associate a control variable with the widget by passing that control variable as the value of this option. See Section 28, Control variables: the values behind the widgets (p. 104). This option specifies the upper limit of a range values. See the from_ option, above, and also the increment option.
insertbackground insertborderwidth
insertofftime insertontime
insertwidth
justify
takefocus
textvariable
to
Tkinter reference
75
values
There are two ways to specify the possible values of the widget. One way is to provide a tuple of strings as the value of the values option. For example, values=('red', 'blue', 'green') would allow only those three strings as values. To configure the widget to accept a range of numeric values, see the from_ option above. Use this option to specify the number of characters allowed in the entry part of the widget. The default value is 20. Normally, when the widget is at its highest value, the up-arrowhead does nothing, and when the widget is at its lowest value, the down-arrowhead does nothing. If you select wrap=True, the up-arrowhead will advance from the highest value back to the lowest, and the down-arrowhead will advance from the lowest value back to the highest. Use this option to connect a scrollbar to the entry part of the widget. For details, see Section 21.2, Connecting a Scrollbar to another widget (p. 73).
width wrap
xscrollcommand
These methods are available on Spinbox widgets: .bbox ( index ) This method returns the bounding box of the character at position index in the entry part of the widget. The result is a tuple (x, y, w, h), where the values are the x and y coordinates of the upper left corner, and the character's width and height in pixels, in that order. .delete ( first, last=None ) This method deletes characters from the entry part of the Spinbox. The values of first and last are interpreted in the standard way for Python slices. .get() This method returns the value of the Spinbox. The value is always returned as a string, even if the widget is set up to contain a number. .icursor ( index ) Use this method to position the insertion cursor at the location specified by index, using the standard Python convention for positions. .identify ( x, y ) Given a position (x, y) within the widget, this method returns a string describing what is at that location. Values may be any of: 'entry' for the entry area. 'buttonup' for the upward-pointing arrowhead. 'buttondown' for the downward-pointing arrowhead. '' (an empty string) if these coordinates are not within the widget. .index ( i ) This method returns the numerical position of an index i. Arguments may be any of: END to get the position after the last character of the entry. INSERT to get the position of the insertion cursor. ANCHOR to get the position of the selection anchor. 'sel.first' to get the position of the start of the selection. If the selection is not within the widget, this method raises a TclError exception. 'sel.last' to get the position just past the end of the selection. If the selection is not within the widget, this method raises a TclError exception.
76
Tkinter reference
A string of the form @x denotes an x-coordinate within the widget. The return value is the position of the character containing that coordinate. If the coordinate is outside the widget altogether, the return value will be the position of the character closest to that position. .insert ( index, text ) This method inserts characters from the string text at the position specified by index. For the possible index values, see the .index() method above. .invoke ( element ) Call this method to get the same effect as the user clicking on an arrowhead. The element argument is 'buttonup' for the up-arrowhead, and 'buttondown' for the down-arrowhead. .scan_dragto ( x ) This method works the same as the .scan_dragto() method described in Section 9, The Entry widget (p. 40). .scan_mark ( x ) This method works the same as the .scan_mark() method described in Section 9, The Entry widget (p. 40). .selection('from', index) Sets the selection anchor in the widget to the position specified by the index. For the possible values of index, see the .index() method above. The initial value of the selection anchor is 0. .selection('to', index) Selects the text between the selection anchor and the given index. .selection('range', start, end) Select the text between the start and end indices. For allowable index values, see the .index() method above. .selection_clear() Clears the selection. .selection_get() Returns the selected text. If there is currently no selection, this method will raise a TclError exception.
Tkinter reference
77
You can even embed a text widget in a window containing any Tkinter widgeteven a frame widget containing other widgets. A window is also treated as a single character. See Section 23.4, Text widget windows (p. 82). To create a text widget as the child of a root window or frame named parent: w = Text ( parent, option, ... ) The constructor returns the new Text widget. Options include: autoseparators If the undo option is set, the autoseparators option controls whether separators are automatically added to the undo stack after each insertion or deletion (if autoseparators=True) or not (if autoseparators=False). For an overview of the undo mechanism, see Section 23.7, The Text widget undo/redo stack (p. 83). The default background color of the text widget. See Section 5.3, Colors (p. 9). The width of the border around the text widget; see Section 5.1, Dimensions (p. 9). The default is two pixels. The cursor that will appear when the mouse is over the text widget. See Section 5.8, Cursors (p. 12). Normally, text selected within a text widget is exported to be the selection in the window manager. Set exportselection=0 if you don't want that behavior. The default font for text inserted into the widget. Note that you can have multiple fonts in the widgets by using tags to change the properties of some text. See Section 5.4, Type fonts (p. 10). The color used for text (and bitmaps) within the widget. You can change the color for tagged regions; this option is just the default. The height of the widget in lines (not pixels!), measured according to the current font size.
font
fg or foreground height
highlightbackground The color of the focus highlight when the text widget does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor The color of the focus highlight when the text widget has the focus. highlightthickness The thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress display of the focus highlight. insertbackground insertborderwidth insertofftime insertontime insertwidth maxundo The color of the insertion cursor. Default is black. Size of the 3-D border around the insertion cursor. Default is 0. The number of milliseconds the insertion cursor is off during its blink cycle. Set this option to zero to suppress blinking. Default is 300. The number of milliseconds the insertion cursor is on during its blink cycle. Default is 600. Width of the insertion cursor (its height is determined by the tallest item in its line). Default is 2 pixels. This option sets the maximum number of operations retained on the undo stack. For an overview of the undo mechanism, see Section 23.7, The Text widget undo/redo stack (p. 83). Set this option to -1 to specify an unlimited number of entries in the undo stack.
78
Tkinter reference
The size of the internal padding added to the left and right of the text area. Default is one pixel. For possible values, see Section 5.1, Dimensions (p. 9). The size of the internal padding added above and below the text area. Default is one pixel. The 3-D appearance of the text widget. Default is relief=SUNKEN; for other values, see Section 5.6, Relief styles (p. 12). The background color to use displaying selected text. The width of the border to use around selected text. The foreground color to use displaying selected text. This option specifies how much extra vertical space is put above each line of text. If a line wraps, this space is added only before the first line it occupies on the display. Default is 0. This option specifies how much extra vertical space to add between displayed lines of text when a logical line wraps. Default is 0. This option specifies how much extra vertical space is added below each line of text. If a line wraps, this space is added only after the last line it occupies on the display. Default is 0. Normally, text widgets respond to keyboard and mouse events; set state=NORMAL to get this behavior. If you set state=DISABLED, the text widget will not respond, and you won't be able to modify its contents programmatically either. This option controls how tab characters position text. See Section 23.6, Setting tabs in a Text widget (p. 82). Normally, focus will visit a text widget (see Section 29, Focus: routing keyboard input (p. 106)). Set takefocus=0 if you do not want focus in the widget. Set this option to True to enable the undo mechanism, or False to disable it. See Section 23.7, The Text widget undo/redo stack (p. 83). The width of the widget in characters (not pixels!), measured according to the current font size. This option controls the display of lines that are too wide. With the default behavior, wrap=CHAR, any line that gets too long will be broken at any character. Set wrap=WORD and it will break the line after the last word that will fit. If you want to be able to create lines that are too long to fit in the window, set wrap=NONE and provide a horizontal scrollbar.
spacing2 spacing3
state
tabs takefocus
xscrollcommand yscrollcommand
To make the text widget horizontally scrollable, set this option to the .set method of the horizontal scrollbar. To make the text widget vertically scrollable, set this option to the .set method of the vertical scrollbar.
Tkinter reference
79
80
Tkinter reference
abcdef The index expression 1.0 + 5 chars refers to the position between e and f. You can omit blanks and abbreviate keywords in these expressions if the result is unambiguous. This example could be abbreviated 1.0+5c. - n chars Similar to the previous form, but the position moves backwards n characters. + n lines Moves n lines past the given index. Tkinter tries to leave the new position in the same column as it was on the line it left, but if the line at the new position is shorter, the new position will be at the end of the line. - n lines Moves n lines before the given index. linestart Moves to the position before the first character of the given index. For example, position current linestart refers to the beginning of the line closest to the mouse pointer. lineend Moves to the position after the last character of the given index. For example, position sel.last lineend refers to the end of the line containing the end of the current selection. wordstart The position before the beginning of the word containing the given index. For example, index 11.44 wordstart refers to the position before the word containing position 44 on line 11. For the purposes of this operation, a word is either a string of consecutive letter, digit, or underbar (_) characters, or a single character that is none of these types.
Tkinter reference
81
82
Tkinter reference
continuing our example, because 12c-5c is 7 cm, if the user keeps pressing the Tab key, the cursor would be positioned at 19cm, 26cm, 33cm, and so on. Normally, text after a tab character is aligned with its left edge on the tab stop, but you can include any of the keywords LEFT, RIGHT, CENTER, or NUMERIC in the list after a distance, and that will change the positioning of the text after each tab. A LEFT tab stop has the default behavior. A RIGHT tab stop will position the text so its right edge is on the stop. A CENTER tab will center the following text on the tab stop. A NUMERIC tab stop will place following text to the left of the stop up until the first period (".") in the textafter that, the period will be centered on the stop, and the rest of the text will positioned to its right. For example, setting tabs=("0.5i", "0.8i", RIGHT, "1.2i", CENTER, "2i", NUMERIC) would set four tab stops: a left-aligned tab stop half an inch from the left side, a right-aligned tab stop 0.8" from the left side, a center-aligned tab stop 1.2" from the left, and a numeric-aligned tab stop 2" from the left.
Tkinter reference
83
unless you call the .update_idletasks() method (see Section 25, Universal widget methods (p. 93)). .compare ( index1, op, index2 ) Compares the positions of two indices in the text widget, and returns true if the relational op holds between index1 and index2. The op specifies what comparison to use, one of: "<", "<=", "==", "!=", ">=", or ">". For example, for a text widget t, t.compare("2.0", "<=", END) returns true if the beginning of the second line is before or at the end of the text in t. .delete ( index1, index2=None ) Deletes text starting just after index1. If the second argument is omitted, only one character is deleted. If a second index is given, deletion proceeds up to, but not including, the character after index2. Recall that indices sit between characters. .dlineinfo ( index ) Returns a bounding box for the line that contains the given index. For the form of the bounding box, and a caution about updating idle tasks, see the definition of the .bbox method above. .edit_modified ( arg=None ) Queries, sets, or clears the modified flag. This flag is used to track whether the contents of the widget have been changed. For example, if you are implementing a text editor in a Text widget, you might use the modified flag to determine whether the contents have changed since you last saved the contents to a file. When called with no argument, this method returns True if the modified flag has been set, False if it is clear. You can also explicitly set the modified flag by passing a True value to this method, or clear it by passing a False value. Any operation that inserts or deletes text, whether by program actions or user actions, or an undo or redo operation, will set the modified flag. .edit_redo() Performs a redo operation. For details, see Section 23.7, The Text widget undo/redo stack (p. 83). .edit_reset() Clears the undo stack. .edit_separator() Pushes a separator onto the undo stack. This separator limits the scope of a future undo operation to include only the changes pushed since the separator was pushed. For details, see Section 23.7, The Text widget undo/redo stack (p. 83). .edit_undo() Reverses all changes to the widget's contents made since the last separator was pushed on the undo stack, or all the way to the bottom of the stack if the stack contains no separators. For details, see Section 23.7, The Text widget undo/redo stack (p. 83). It is an error if the undo stack is empty. .image_create ( index[, option=value, ...] ) This method inserts an image into the widget. The image is treated as just another character, whose size is the image's natural size. The options for this method are shown in the table below. You may pass either a series of option=value arguments, or a dictionary of option names and values. align This option specifies how the image is to be aligned vertically if its height is less than the height of its containing line. Values may be top to align it at the top of its space; center
84
Tkinter reference
to center it; bottom to place it at the bottom; or baseline to line up the bottom of the image with the text baseline. image The image to be used. See Section 5.9, Images (p. 14). name You can assign a name to this instance of the image. If you omit this option, Tkinter will generate a unique name. If you create multiple instances of an image in the same Text widget, Tkinter will generate a unique name by appending a # followed by a number. If supplied, this option is a number of pixels of extra space to be added on both sides of the image. If supplied, this option is a number of pixels of extra space to be added above and below the image.
padx pady
.get ( index1, index2=None ) Use this method to retrieve the current text from the widget. Retrieval starts at index index1. If the second argument is omitted, you get the character after index1. If you provide a second index, you get the text between those two indices. Embedded images and windows (widgets) are ignored. .image_cget ( index, option ) To retrieve the current value of an option set on an embedded image, call this method with an index pointing to the image and the name of the option. .image_configure ( index, option, ... ) To set one or more options on an embedded image, call this method with an index pointing to the image as the first argument, and one or more option=value pairs. If you specify no options, you will get back a dictionary defining all the options on the image, and the corresponding values. .image_names() This method returns a tuple of the names of all the text widget's embedded images. .index ( i ) For an index i, this method returns the equivalent position in the form "line.char". .insert ( index, text, tags=None ) Inserts the given text at the given index. If you omit the tags argument, the newly inserted text will be tagged with any tags that apply to the characters both before and after the insertion point. If you want to apply one or more tags to the text you are inserting, provide as a third argument a tuple of tag strings. Any tags that apply to existing characters around the insertion point are ignored. Note: The third argument must be a tuple. If you supply a list argument, Tkinter will silently fail to apply the tags. If you supply a string, each character will be treated as a tag. .mark_gravity ( mark, gravity=None ) Changes or queries the gravity of an existing mark; see Section 23.2, Text widget marks (p. 81), above, for an explanation of gravity. To set the gravity, pass in the name of the mark, followed by either LEFT or RIGHT. To find the gravity of an existing mark, omit the second argument and the method returns LEFT or RIGHT. .mark_names() Returns a sequence of the names of all the marks in the window, including INSERT and CURRENT. .mark_next ( index ) Returns the name of the mark following the given index; if there are no following marks, the method returns an empty string.
Tkinter reference
85
If the index is in numeric form, the method returns the first mark at that position. If the index is a mark, the method returns the next mark following that mark, which may be at the same numerical position. .mark_previous ( index ) Returns the name of the mark preceding the given index. If there are no preceding marks, the method returns an empty string. If the index is in numeric form, the method returns returns the last mark at that position. If the index is a mark, the method returns the preceding mark, which may be at the same numerical position. .mark_set ( mark, index ) If no mark with name mark exists, one is created with RIGHT gravity and placed where index points. If the mark already exists, it is moved to the new location. This method may change the position of the INSERT or CURRENT indices. .mark_unset ( mark ) Removes the named mark. This method cannot be used to remove the INSERT or CURRENT marks. .scan_dragto ( x, y ) See .scan_mark, below. .scan_mark ( x, y ) This method is used to implement fast scrolling of a Text widget. Typically, a user presses and holds a mouse button at some position in the widget, and then moves the mouse in the desired direction, and the widget moves in that direction at a rate proportional to the distance the mouse has moved since the button was depressed. The motion may be any combination of vertical or horizontal scrolling. To implement this feature, bind a mouse button down event to a handler that calls .scan_mark(x, y), where x and y are the current mouse position. Then bind the <Motion> event to a handler that calls .scan_dragto(x, y), where x and y are the new mouse position. .search ( pattern, index, option, ... ) Searches for pattern (which can be either a string or a regular expression) in the buffer starting at the given index. If it succeeds, it returns an index of the "line.char" form; if it fails, it returns an empty string. The allowable options for this method are: backwards Set this option to True to search backwards from the index. Default is forwards. count If you set this option to an IntVar control variable, when there is a match you can retrieve the length of the text that matched by using the .get() method on that variable after the method returns. Set this option to True to search for text that exactly matches the pattern. This is the default option. Compare the regexp option below. Set this option to True to search forwards from the index. This is the default option. Set this option to True to interpret the pattern as a Tcl-style regular expression. The default is to look for an exact match to pattern. Tcl regular expressions are a subset of Python regular expressions, supporting these features: . ^ [c1] () * + ? e1|e2 Set this option to 1 to ignore case. The default is a case-sensitive search.
nocase
86
Tkinter reference
stopindex To limit the search, set this option to the index beyond which the search should not go. .see ( index ) If the text containing the given index is not visible, scroll the text until that text is visible. .tag_add ( tagName, index1, index2=None ) This method associates the tag named tagName with a region of the contents starting just after index index1 and extending up to index index2. If you omit index2, only the character after index1 is tagged. .tag_bind ( tagName, sequence, func, add=None ) This method binds an event to all the text tagged with tagName. See Section 30, Events (p. 107), below, for more information on event bindings. To create a new binding for tagged text, use the first three arguments: sequence identifies the event, and func is the function you want it to call when that event happens. To add another binding to an existing tag, pass the same first three arguments and "+" as the fourth argument. To find out what bindings exist for a given sequence on a tag, pass only the first two arguments; the method returns the associated function. To find all the bindings for a given tag, pass only the first argument; the method returns a list of all the tag's sequence arguments. .tag_cget ( tagName, option ) Use this method to retrieve the value of the given option for the given tagName. .tag_config ( tagName, option, ... ) To change the value of options for the tag named tagName, pass in one or more option=value pairs. If you pass only one argument, you will get back a dictionary defining all the options and their values currently in force for the named tag. Here are the options for tag configuration: background bgstipple The background color for text with this tag. Note that you can't use bg as an abbreviation. To make the background appear grayish, set this option to one of the standard bitmap names (see Section 5.7, Bitmaps (p. 12)). This has no effect unless you also specify a background.
borderwidth Width of the border around text with this tag. Default is 0. Note that you can't use bd as an abbreviation. fgstipple font foreground justify lmargin1 To make the text appear grayish, set this option a bitmap name. The font used to display text with this tag. See Section 5.4, Type fonts (p. 10). The color used for text with this tag. Note that you can't use the fg abbreviation here. The justify option set on the first character of each line determines how that line is justified: LEFT (the default), CENTER, or RIGHT. How much to indent the first line of a chunk of text that has this tag. The default is 0. See Section 5.1, Dimensions (p. 9)for allowable values.
Tkinter reference
87
lmargin2 offset
How much to indent successive lines of a chunk of text that has this tag. The default is 0. How much to raise (positive values) or lower (negative values) text with this tag relative to the baseline. Use this to get superscripts or subscripts, for example. For allowable values, see Section 5.1, Dimensions (p. 9). Set overstrike=1 to draw a horizontal line through the center of text with this tag. Which 3-D effect to use for text with this tag. The default is relief=FLAT; for other possible values see Section 5.6, Relief styles (p. 12). Size of the right margin for chunks of text with this tag. Default is 0. This option specifies how much extra vertical space is put above each line of text with this tag. If a line wraps, this space is added only before the first line it occupies on the display. Default is 0. This option specifies how much extra vertical space to add between displayed lines of text with this tag when a logical line wraps. Default is 0. This option specifies how much extra vertical space is added below each line of text with this tag. If a line wraps, this space is added only after the last line it occupies on the display. Default is 0. How tabs are expanded on lines with this tag. See Section 23.6, Setting tabs in a Text widget (p. 82). Set underline=1 to underline text with this tag. How long lines are wrapped in text with this tag. See the description of the wrap option for text widgets, above.
spacing2 spacing3
.tag_delete ( tagName, ... ) To delete one or more tags, pass their names to this method. Their options and bindings go away, and the tags are removed from all regions of text. .tag_lower ( tagName, belowThis=None ) Use this method to change the order of tags in the tag stack (see Section 23.5, Text widget tags (p. 82), above, for an explanation of the tag stack). If you pass two arguments, the tag with name tagName is moved to a position just below the tag with name belowThis. If you pass only one argument, that tag is moved to the bottom of the tag stack. .tag_names ( index=None ) If you pass an index argument, this method returns a sequence of all the tag names that are associated with the character after that index. If you pass no argument, you get a sequence of all the tag names defined in the text widget. .tag_nextrange ( tagName, index1, index2=None ) This method searches a given region for places where a tag named tagName starts. The region searched starts at index index1 and ends at index index2. If the index2 argument is omitted, the search goes all the way to the end of the text. If there is a place in the given region where that tag starts, the method returns a sequence [i0, i1], where i0 is the index of the first tagged character and i1 is the index of the position just after the last tagged character. If no tag starts are found in the region, the method returns an empty string.
88
Tkinter reference
.tag_prevrange ( tagName, index1, index2=None ) This method searches a given region for places where a tag named tagName starts. The region searched starts before index index1 and ends at index index2. If the index2 argument is omitted, the search goes all the way to the end of the text. The return values are as in .tag_nextrange(). .tag_raise ( tagName, aboveThis=None ) Use this method to change the order of tags in the tag stack (see Section 23.5, Text widget tags (p. 82), above, for an explanation of the tag stack). If you pass two arguments, the tag with name tagName is moved to a position just above the tag with name aboveThis. If you pass only one argument, that tag is moved to the top of the tag stack. .tag_ranges ( tagName ) This method finds all the ranges of text in the widget that are tagged with name tagName, and returns a sequence [s0, e0, s1, e1, ], where each si is the index just before the first character of the range and ei is the index just after the last character of the range. .tag_remove ( tagName, index1, index2=None ) Removes the tag named tagName from all characters between index1 and index2. If index2 is omitted, the tag is removed from the single character after index1. .tag_unbind ( tagName, sequence, funcid=None ) Remove the event binding for the given sequence from the tag named tagName. If there are multiple handlers for this sequence and tag, you can remove only one handler by passing it as the third argument. .window_cget ( index, option ) Returns the value of the given option for the embedded widget at the given index. .window_configure ( index, option ) To change the value of options for embedded widget at the given index, pass in one or more option=value pairs. If you pass only one argument, you will get back a dictionary defining all the options and their values currently in force for the given widget. .window_create ( index, option, ... ) This method creates a window where a widget can be embedded within a text widget. There are two ways to provide the embedded widget: a. you can use pass the widget to the window option in this method, or b. you can define a procedure that will create the widget and pass that procedure as a callback to the create option. Options for .window_create() are: align Specifies how to position the embedded widget vertically in its line, if it isn't as tall as the text on the line. Values include: align=CENTER (the default), which centers the widget vertically within the line; align=TOP, which places the top of the image at the top of the line; align=BOTTOM, which places the bottom of the image at the bottom of the line; and align=BASELINE, which aligns the bottom of the image with the text baseline. A procedure that will create the embedded widget on demand. This procedure takes no arguments and must create the widget as a child of the text widget and return the widget as its result. Extra space added to the left and right of the widget within the text line. Default is 0.
create
padx
Tkinter reference
89
pady
Extra space added above and below the widget within the text line. Default is 0.
stretch This option controls what happens when the line is higher than the embedded widget. Normally this option is 0, meaning that the embedded widget is left at its natural size. If you set stretch=1, the widget is stretched vertically to fill the height of the line, and the align option is ignored. window The widget to be embedded. This widget must be a child of the text widget.
.window_names() Returns a sequence containing the names of all embedded widgets. .xview ( MOVETO, fraction ) This method scrolls the text widget horizontally, and is intended for binding to the command option of a related horizontal scrollbar. This method can be called in two different ways. The first call positions the text at a value given by fraction, where 0.0 moves the text to its leftmost position and 1.0 to its rightmost position. .xview ( SCROLL, n, what ) The second call moves the text left or right: the what argument specifies how much to move and can be either UNITS or PAGES, and n tells how many characters or pages to move the text to the right relative to its image (or left, if negative). .xview_moveto ( fraction ) This method scrolls the text in the same way as .xview(MOVETO, fraction). .xview_scroll ( n, what ) Same as .xview(SCROLL, n, what). .yview(MOVETO, fraction) The vertical scrolling equivalent of .xview(MOVETO,). .yview(SCROLL, n, what) The vertical scrolling equivalent of .xview(SCROLL,). When scrolling vertically by UNITS, the units are lines. .yview_moveto(fraction) The vertical scrolling equivalent of .xview_moveto(). .yview_scroll(n, what) The vertical scrolling equivalent of .xview_scroll().
90
Tkinter reference
bd or borderwidth class_
Border width in pixels; default is 0. For possible values, see Section 5.1, Dimensions (p. 9). See also the relief option, below. You can give a Toplevel window a class name. Such names are matched against the option database, so your application can pick up the user's configuration preferences (such as colors) by class name. For example, you might design a series of pop-ups called screamers, and set them all up with class_="Screamer". Then you can put a line in your option database like this: *Screamer*background: red and then, if you use the .option_readfile() method to read your option database, all widgets with that class name will default to a red background. This option is named class_ because class is a reserved word in Python.
cursor height
The cursor that appears when the mouse is in this window. See Section 5.8, Cursors (p. 12). Window height; see Section 5.1, Dimensions (p. 9).
highlightbackground The color of the focus highlight when the window does not have focus. See Section 29, Focus: routing keyboard input (p. 106). highlightcolor highlightthickness menu The color of the focus highlight when the window has the focus. The thickness of the focus highlight. Default is 1. Set highlightthickness=0 to suppress display of the focus highlight. To provide this window with a top-level menubar, supply a Menu widget as the value of this option. Under MacOS, this menu will appear at the top of the screen when the window is active. Under Windows or Unix, it will appear at the top of the application. Use this option to provide extra space on the left and right sides of the window. The value is a number of pixels. Use this option to provide extra space on the top and bottom sides of the window. The value is a number of pixels. Normally, a top-level window will have no 3-d borders around it. To get a shaded border, set the bd option larger that its default value of zero, and set the relief option to one of the constants discussed under Section 5.6, Relief styles (p. 12). Normally, a top-level window does not get focus. Use takefocus=True if you want it to be able to take focus; see Section 29, Focus: routing keyboard input (p. 106). The desired width of the window; see Section 5.1, Dimensions (p. 9).
takefocus
width
These methods are available for top-level windows: .aspect ( nmin, dmin, nmax, dmax ) Constrain the root window's width:length ratio to the range [ nmin / dmin, nmax / dmax ]. .deiconify() If this window is iconified, expand it. .geometry ( newGeometry=None ) Set the window geometry. For the form of the argument, see Section 5.10, Geometry strings (p. 14). If the argument is omitted, the current geometry string is returned.
Tkinter reference
91
.iconify() Iconify the window. .lift ( aboveThis=None ) To raise this window to the top of the stacking order in the window manager, call this method with no arguments. You can also raise it to a position in the stacking order just above another Toplevel window by passing that window as an argument. .lower ( belowThis=None ) If the argument is omitted, moves the window to the bottom of the stacking order in the window manager. You can also move the window to a position just under some other top-level window by passing that Toplevel widget as an argument. .maxsize ( width=None, height=None ) Set the maximum window size. If the arguments are omitted, returns the current (width, height). .minsize ( width=None, height=None ) Set the minimum window size. If the arguments are omitted, returns the current minima as a 2tuple. .overrideredirect ( flag=None ) If called with a True argument, this method sets the override redirect flag, which removes all window manager decorations from the window, so that it cannot be moved, resized, iconified, or closed. If called with a False argument, window manager decorations are restored and the override redirect flag is cleared. If called with no argument, it returns the current state of the override redirect flag. Be sure to call the .update_idletasks() method (see Section 25, Universal widget methods (p. 93)) before setting this flag. If you call it before entering the main loop, your window will be disabled before it ever appears. This method may not work on some Unix and MacOS platforms. .resizable ( width=None, height=None ) If width is true, allow horizontal resizing. If height is true, allow vertical resizing. If the arguments are omitted, returns the current size as a 2-tuple. .state(newstate=None) Returns the window's current state, one of: "normal": Displayed normally. "iconic": Iconified with the .iconify() method. "withdrawn": Hidden; see the .withdraw() method below. To change the window's state, pass one of the strings above as an argument to the method. For example, to iconify a Toplevel instance T, use T.state("iconify") . .title ( text=None ) Set the window title. If the argument is omitted, returns the current title. .transient ( parent=None ) Make this window a transient window for some parent window; the default parent window is this window's parent. This method is useful for short-lived pop-up dialog windows. A transient window always appears in front of its parent. If the parent window is iconified, the transient is iconified as well. .withdraw() Hides the window. Restore it with .deiconify() or .iconify().
92
Tkinter reference
http://docs.python.org/library/time.html
Tkinter reference
93
w.clipboard_clear() Clears the display's clipboard (see .clipboard_append() above). w.column_configure() See Section 4.2, Other grid management methods (p. 6). w.config( option=value, ... ) Same as .configure(). w.configure ( option=value, ... ) Set the values of one or more options. For the options whose names are Python reserved words (class, from, in), use a trailing underbar: "class_", "from_", "in_". You can also set the value of an option for widget w with the statement w[option] = value If you call the .config() method on a widget with no arguments, you'll get a dictionary of all the widget's current options. The keys are the option names (including aliases like bd for borderwidth). The value for each key is: for most entries, a five-tuple: (option name, option database key, option database class, default value, current value); or, for alias names (like "fg"), a two-tuple: (alias name, equivalent standard name). w.destroy() Calling w.destroy() on a widget w destroys w and all its children. w.event_add ( virtual, *sequences ) This method creates a virtual event whose name is given by the virtual string argument. Each additional argument describes one sequence, that is, the description of a physical event. When that event occurs, the new virtual event is triggered. See Section 30, Events (p. 107) for a general description of virtual events. w.event_delete ( virtual, *sequences ) Deletes physical events from the virtual event whose name is given by the string virtual. If all the physical events are removed from a given virtual event, that virtual event won't happen anymore. w.event_generate ( sequence, **kw ) This method causes an event to trigger without any external stimulus. The handling of the event is the same as if it had been triggered by an external stimulus. The sequence argument describes the event to be triggered. You can set values for selected fields in the Event object by providing keyword=value arguments, where the keyword specifies the name of a field in the Event object. See Section 30, Events (p. 107) for a full discussion of events. w.event_info ( virtual=None ) If you call this method without an argument, you'll get back a sequence of all the currently defined virtual event names. To retrieve the physical events associated with a virtual event, pass this method the name of the virtual event and you will get back a sequence of the physical sequence names, or None if the given virtual event has never been defined. w.focus_displayof() Returns the name of the window that currently has input focus on the same display as the widget. If no such window has input focus, returns None. See Section 29, Focus: routing keyboard input (p. 106) for a general description of input focus.
94
Tkinter reference
w.focus_force() Force the input focus to the widget. This is impolite. It's better to wait for the window manager to give you the focus. See also .grab_set_global() below. w.focus_get() Get the name of the widget that has focus in this application, if anyotherwise return None. w.focus_lastfor() This method retrieves the name of the widget that last had the input focus in the top-level window that contains w. If none of this top-level's widgets have ever had input focus, it returns the name of the top-level widget. If this application doesn't have the input focus, .focus_lastfor() will return the name of the widget that will get the focus next time it comes back to this application. w.focus_set() If w's application has the input focus, the focus will jump to w. If w's application doesn't have focus, Tk will remember to give it to w next the application gets focus. w.grab_current() If there is a grab in force for w's display, return its identifier, otherwise return None. Refer to Section 30, Events (p. 107) for a discussion of grabs. w.grab_release() If w has a grab in force, release it. w.grab_set() Widget w grabs all events for w's application. If there was another grab in force, it goes away. See Section 30, Events (p. 107) for a discussion of grabs. w.grab_set_global() Widget w grabs all events for the entire screen. This is considered impolite and should be used only in great need. Any other grab in force goes away. Try to use this awesome power only for the forces of good, and never for the forces of evil, okay? w.grab_status() If there is a local grab in force (set by .grab_set()), this method returns the string "local". If there is a global grab in force (from .grab_set_global()), it returns "global". If no grab is in force, it returns None. w.grid_forget() See Section 4.2, Other grid management methods (p. 6). w.grid_propagate() See Section 4.2, Other grid management methods (p. 6). w.grid_remove() See Section 4.2, Other grid management methods (p. 6). w.image_names() Returns the names of all the images in w's application as a sequence of strings. w.keys() Returns the option names for the widget as a sequence of strings. w.lift ( aboveThis=None ) If the argument is None, the window containing w is moved to the top of the window stacking order. To move the window just above some Toplevel window w, pass w as an argument. w.lower ( belowThis=None ) If the argument is None, the window containing w is moved to the bottom of the window stacking order. To move the window just below some Toplevel window w, pass w as an argument.
Tkinter reference
95
w.mainloop() This method must be called, generally after all the static widgets are created, to start processing events. You can leave the main loop with the .quit() method (below). You can also call this method inside an event handler to resume the main loop. w.nametowidget ( name ) This method returns the actual widget whose path name is name. See Section 5.11, Window names (p. 15). If the name is unknown, this method will raise KeyError. w.option_add ( pattern, value, priority=None ) This method adds default option values to the Tkinter option database. The pattern is a string that specifies a default value for options of one or more widgets. The priority values are one of: 20 For global default properties of widgets. 40 For default properties of specific applications. 60 For options that come from user files such as their .Xdefaults file. 80 For options that are set after the application starts up. This is the default priority level. Higher-level priorities take precedence over lower-level ones. See Section 26, Standardizing appearance (p. 100) for an overview of the option database. The syntax of the pattern argument to .option_add() is the same as the option-pattern part of the resource specification line. For example, to get the effect of this resource specification line: *Button*font: times 24 bold your application (self in this example) might include these lines: self.bigFont = tkFont.Font ( family="times", size=24, weight="bold" ) self.option_add ( "*Button*font", self.bigFont ) Any Button widgets created after executing these lines would default to bold Times 24 font (unless overriden by a font option to the Button constructor). w.option_clear() This method removes all options from the Tkinter option database. This has the effect of going back to all the default values. w.option_get ( name, classname ) Use this method to retrieve the current value of an option from the Tkinter option database. The first argument is the instance key and the second argument is the class key. If there are any matches, it returns the value of the option that best matches. If there are no matches, it returns "". Refer to Section 26, Standardizing appearance (p. 100) for more about how keys are matched with options. w.option_readfile ( fileName, priority=None ) As a convenience for user configuration, you can designate a named file where users can put their preferred options, using the same format as the .Xdefaults file. Then, when your application is initializing, you can pass that file's name to this method, and the options from that file will be added to the database. If the file doesn't exist, or its format is invalid, this method will raise TclError. Refer to Section 26, Standardizing appearance (p. 100) for an introduction to the options database and the format of option files.
96
Tkinter reference
w.quit() This method exits the main loop. See .mainloop(), above, for a discussion of main loops. w.rowconfigure() See Section 4.2, Other grid management methods (p. 6). w.selection_clear() If w currently has a selection (such as a highlighted segment of text in an entry widget), clear that selection. w.selection_get() If w currently has a selection, this method returns the selected text. If there is no selection, it raises TclError. w.selection_own() Make w the owner of the selection in w's display, stealing it from the previous owner, if any. w.selection_own_get() Returns the widget that currently owns the selection in w's display. Raises TclError if there is no such selection. w.tk_focusFollowsMouse() Normally, the input focus cycles through a sequence of widgets determined by their hierarchy and creation order; see Section 29, Focus: routing keyboard input (p. 106). You can, instead, tell Tkinter to force the focus to be wherever the mouse is; just call this method. There is no easy way to undo it, however. w.tk_focusNext() Returns the widget that follows w in the focus traversal sequence. Refer to Section 29, Focus: routing keyboard input (p. 106) for a discussion of focus traversal. w.tk_focusPrev() Returns the widget that precedes w in the focus traversal sequence. w.unbind ( sequence, funcid=None ) This method deletes bindings on w for the event described by sequence. If the second argument is a callback bound to that sequence, that callback is removed and the rest, if any, are left in place. If the second argument is omitted, all bindings are deleted. See Section 30, Events (p. 107), below, for a general discussion of event bindings. w.unbind_all ( sequence ) Deletes all event bindings throughout the application for the event described by the given sequence. w.unbind_class ( className, sequence ) Like .unbind(), but applies to all widgets named className (e.g., "Entry" or "Listbox"). w.update() This method forces the updating of the display. It should be used only if you know what you're doing, since it can lead to unpredictable behavior or looping. It should never be called from an event callback or a function that is called from an event callback. w.update_idletasks() Some tasks in updating the display, such as resizing and redrawing widgets, are called idle tasks because they are usually deferred until the application has finished handling events and has gone back to the main loop to wait for new events. If you want to force the display to be updated before the application next idles, call the w.update_idletasks() method on any widget.
Tkinter reference
97
w.wait_variable ( v ) Waits until the value of variable v is set, even if the value does not change. This method enters a local wait loop, so it does not block the rest of the application. w.wait_visibility ( w ) Wait until widget w (typically a Toplevel) is visible. w.wait_window ( w ) Wait until window w is destroyed. w.winfo_children() Returns a list of all w's children, in their stacking order from lowest (bottom) to highest (top). w.winfo_class() Returns w's class name (e.g., "Button"). w.winfo_containing ( rootX, rootY, displayof=0 ) This method is used to find the window that contains point (rootX, rootY). If the displayof option is false, the coordinates are relative to the application's root window; if true, the coordinates are treated as relative to the top-level window that contains w. If the specified point is in one of the application's top-level window, this method returns that window; otherwise it returns None. w.winfo_depth() Returns the number of bits per pixel in w's display. w.winfo_fpixels ( number ) For any dimension number (see Section 5.1, Dimensions (p. 9)), this method returns that distance in pixels on w's display, as a floating-point number. w.winfo_geometry() Returns the geometry string describing the size and on-screen location of w. See Section 5.10, Geometry strings (p. 14).
Warning
The geometry is not accurate until the application has updated its idle tasks. In particular, all geometries are initially "1x1+0+0" until the widgets and geometry manager have negotiated their sizes and positions. See the .update_idletasks() method, above, in this section to see how to insure that the widget's geometry is up to date. w.winfo_height() Returns the current height of w in pixels. See the remarks on geometry updating under .winfo_geometry(), above. You may prefer to use .winfo_reqheight(), described below, which is always up to date. w.winfo_id() Returns an integer that uniquely identifies w within its top-level window. You will need this for the .winfo_pathname() method, below. w.winfo_ismapped() This method returns true if w is mapped, false otherwise. A widget is mapped if it has been gridded (or placed or packed, if you are using one of the other geometry managers) into its parent, and if its parent is mapped, and so on up to the top-level window.
98
Tkinter reference
w.winfo_manager() If w has not been gridded (or placed via one of the other geometry managers), this method returns an empty string. If w has been gridded or otherwise placed, it returns a string naming the geometry manager for w: this value will be one of "grid", "pack", "place", "canvas", or "text". w.winfo_name() This method returns w's name relative to its parent. See Section 5.11, Window names (p. 15). Also see .winfo_pathname(), below, to find out how to obtain a widget's path name. w.winfo_parent() Returns w's parent's path name, or an empty string if w is a top-level window. See Section 5.11, Window names (p. 15) above, for more on widget path names. w.winfo_pathname ( id, displayof=0 ) If the displayof argument is false, returns the window path name of the widget with unique identifier id in the application's main window. If displayof is true, the id number specifies a widget in the same top-level window as w. See Section 5.11, Window names (p. 15) for a discussion of widget path names. w.winfo_pixels ( number ) For any dimension number (see Dimensions, above), this method returns that distance in pixels on w's display, as an integer. w.winfo_pointerx() Returns the same value as the x coordinate returned by .winfo_pointerxy(). w.winfo_pointerxy() Returns a tuple (x, y) containing the coordinates of the mouse pointer relative to w's root window. If the mouse pointer isn't on the same screen, returns (-1, -1). w.winfo_pointery() Returns the same value as the y coordinate returned by .winfo_pointerxy(). w.winfo_reqheight() These methods return the requested height of widget w. This is the minimum height necessary so that all of w's contents have the room they need. The actual height may be different due to negotiations with the geometry manager. w.winfo_reqwidth() Returns the requested width of widget w, the minimum width necessary to contain w. As with .winfo_reqheight(), the actual width may be different due to negotiations with the geometry manager. w.winfo_rgb ( color ) For any given color, this method returns the equivalent red-green-blue color specification as a 3tuple (r, g, b), where each number is an integer in the range [0, 65536). For example, if the color is "green", this method returns the 3-tuple (0, 65535, 0). For more on specifying colors, see Section 5.3, Colors (p. 9). w.winfo_rootx() Returns the x coordinates of the left-hand side of w's root window relative to w's parent. If w has a border, this is the outer edge of the border. w.winfo_rooty() Returns the y coordinate of the top side of w's root window relative to w's parent. If w has a border, this is the top edge of the border.
Tkinter reference
99
w.winfo_screenheight() Returns the height of the screen in pixels. w.winfo_screenmmheight() Returns the height of the screen in millimeters. w.winfo_screenmmwidth() Returns the width of the screen in millimeters. w.winfo_screenvisual() Returns a string that describes the display's method of color rendition. This is usually "truecolor" for 16- or 24-bit displays, "pseudocolor" for 256-color displays. w.winfo_screenwidth() Returns the width of the screen in pixels. w.winfo_toplevel() Returns the top-level window containing w. That window supports all the methods on Toplevel widgets; see Section 24, Toplevel: Top-level window methods (p. 90). w.winfo_viewable() A predicate that returns a True value if w is viewable, that is, if it and all its ancestors in the same Toplevel are mapped. w.winfo_width() Returns the current width of w in pixels. See the remarks on geometry updating under .winfo_geometry(), above. You may prefer to use the .winfo_reqwidth() method, described above; it is always up to date. w.winfo_x() Returns the x coordinate of the left side of w relative to its parent. If w has a border, this is the outer edge of the border. w.winfo_y() Returns the y coordinate of the top side of w relative to its parent. If w has a border, this is the outer edge of the border.
100
Tkinter reference
ureif the designer adds new widgets, the user would have to describe every property of every new widget. So, the option database allows the programmer and the user to specify general patterns describing which widgets to configure. These patterns operate on the names of the widgets, but widgets are named using two parallel naming schemes: a. Every widget has a class name. By default, the class name is the same as the class constructor: "Button" for buttons, "Frame" for a frame, and so on. However, you can create new classes of widgets, usually inheriting from the Frame class, and give them new names of your own creation. See Section 26.1, How to name a widget class (p. 101) for details. b. You can also give any widget an instance name. The default name of a widget is usually a meaningless number (see Section 5.11, Window names (p. 15)). However, as with widget classes, you can assign a name to any widget. See the section Section 26.2, How to name a widget instance (p. 101) for details. Every widget in every application therefore has two hierarchies of namesthe class name hierarchy and the instance name hierarchy. For example, a button embedded in a text widget which is itself embedded in a frame would have the class hierarchy Frame.Text.Button. It might also have an instance hierarchy something like .mainFrame.messageText.panicButton if you so named all the instances. The initial dot stands for the root window; see Section 5.11, Window names (p. 15) for more information on window path names. The option database mechanism can make use of either class names or instance names in defining options, so you can make options apply to whole classes (e.g., all buttons have a blue background) or to specific instances (e.g., the Panic Button has red letters on it). After we look at how to name classes and instances, in Section 26.3, Resource specification lines (p. 102), we'll discuss how the options database really works.
Tkinter reference
101
102
Tkinter reference
In the next section we'll talk about how Tkinter figures out exactly which option value to use if there are multiple resource specification lines that apply.
Tkinter reference
103
The sequence of events for using a Button widget is very specific, though. The user must move the mouse pointer onto the widget with mouse button 1 up, then press mouse button 1, and then release mouse button 1 while still on the widget. No other sequence of events will press a Button widget. There is a much more general mechanism that can let your application react to many more kinds of inputs: the press or release of any keyboard key or mouse button; movement of the mouse into, around, or out of a widget; and many other events. As with command handlers, in this mechanism you write handler procedures that will be called whenever certain types of events occur. This mechanism is discussed under Section 30, Events (p. 107). Many widgets require you to use control variables, special objects that connect widgets together and to your program, so that you can read and set properties of the widgets. Control variables will be discussed in the next section.
All control variables have these two methods: .get() Returns the current value of the variable. .set ( value ) Changes the current value of the variable. If any widget options are slaved to this variable, those widgets will be updated when the main loop next idles; see .update_idletasks() in Section 25, Universal widget methods (p. 93) for more information on controlling this update cycle.
104
Tkinter reference
Here are some comments on how control variables are used with specific widgets: Button You can set its textvariable to a StringVar. Anytime that variable is changed, the text on the button will be updated to display the new value. This is not necessary unless the button's text is actually going to change: use the text attribute if the button's label is static. Checkbutton Normally, you will set the widget's variable option to an IntVar, and that variable will be set to 1 when the checkbutton is turned on and to 0 when it is turned off. However, you can pick different values for those two states with the onvalue and offvalue options, respectively. You can even use a StringVar as the checkbutton's variable, and supply string values for the offvalue and onvalue. Here's an example: self.spamVar = StringVar() self.spamCB = Checkbutton ( self, text="Spam?", variable=self.spamVar, onvalue="yes", offvalue="no" ) If this checkbutton is on, self.spamVar.get() will return the string "yes"; if the checkbutton is off, that same call will return the string "no". Furthermore, your program can turn the checkbutton on by calling .set("yes"). You can also the textvariable option of a checkbutton to a StringVar. Then you can change the text label on that checkbutton using the .set() method on that variable. Entry Set its textvariable option to a StringVar. Use that variable's .get() method to retrieve the text currently displayed in the widget. You can also the variable's .set() method to change the text displayed in the widget. Label You can set its textvariable option to a StringVar. Then any call to the variable's .set() method will change the text displayed on the label. This is not necessary if the label's text is static; use the text attribute for labels that don't change while the application is running. Menubutton If you want to be able to change the text displayed on the menu button, set its textvariable option to a StringVar and use that variable's .set() method to change the displayed text. Radiobutton The variable option must be set to a control variable, either an IntVar or a StringVar. All the radiobuttons in a functional group must share the same control variable. Set the value option of each radiobutton in the group to a different value. Whenever the user sets a radiobutton, the variable will be set to the value option of that radiobutton, and all the other radiobuttons that share the group will be cleared. You might wonder, what state is a group of radiobuttons in when the control variable has never been set and the user has never clicked on them? Each control variable has a default value: 0 for an IntVar, 0.0 for a DoubleVar, and "" for a StringVar. If one of the radiobuttons has that value, that radiobutton will be set initially. If no radiobutton's value option matches the value of the variable, the radiobuttons will all appear to be cleared. If you want to change the text label on a radiobutton during the execution of your application, set its textvariable option to a StringVar. Then your program can change the text label by passing the new label text to the variable's .set() method.
Tkinter reference
105
Scale For a scale widget, set its variable option to a control variable of any class, and set its from_ and to options to the limiting values for the opposite ends of the scale. For example, you could use an IntVar and set the scale's from_=0 and to=100. Then every user change to the widget would change the variable's value to some value between 0 and 100 inclusive. Your program can also move the slider by using the .set() method on the control variable. To continue the above example, .set(75) would move the slider to a position three-fourths of the way along its trough. To set up a Scale widget for floating values, use a DoubleVar. You can use a StringVar as the control variable of a Scale widget. You will still need to provide numeric from_ and to values, but the numeric value of the widget will be converted to a string for storage in the StringVar. Use the scale's digits option to control the precision of this conversion.
106
Tkinter reference
Widgets of class Frame, Label, and Menu are not normally visited by the focus. However, you can set their takefocus options to 1 to get them included in focus traversal. You can also take any widget out of focus traversal by setting its takefocus option to 0. The order in which the tab key traverses the widgets is: For widgets that are children of the same parent, focus goes in the same order the widgets were created. For parent widgets that contain other widgets (such as frames), focus visits the parent widget first (unless its takefocus option is 0), then it visits the child widgets, recursively, in the order they were created. To sum up: to set up the focus traversal order of your widgets, create them in that order. Remove widgets from the traversal order by setting their takefocus options to 0, and for those whose default takefocus option is 0, set it to 1 if you want to add them to the order. The above describes the default functioning of input focus in Tkinter. There is another, completely different way to handle itlet the focus go wherever the mouse goes. Under Section 25, Universal widget methods (p. 93), refer to the .tk_focusFollowsMouse() method. You can also add, change or delete the way any key on the keyboard functions inside any widget by using event bindings. See Section 30, Events (p. 107) for the details.
Tkinter reference
107
The first argument is a sequence descriptor that tells Tkinter that whenever the middle mouse button goes down, it is to call the event handler named self.__drawOrangeBlob. (See Section 30.6, Writing your handler: The Event class (p. 113), below, for an overview of how to write handlers such as .__drawOrangeBlob()). Note that you omit the parentheses after the handler name, so that Python will pass in a reference the handler instead of trying to call it right away. 2. Class binding: You can bind an event to all widgets of a class. For example, you might set up all Button widgets to respond to middle mouse button clicks by changing back and forth between English and Japanese labels. To bind an event to all widgets of a class, call the .bind_class() method on any widget (see Section 25, Universal widget methods (p. 93), above). For example, suppose you have several canvases, and you want to set up mouse button 2 to draw an orange blob in any of them. Rather than having to call .bind() for every one of them, you can set them all up with one call something like this: self.bind_class ( "Canvas", "<Button-2>", self.__drawOrangeBlob ) 3. Application binding: You can set up a binding so that a certain event calls a handler no matter what widget has the focus or is under the mouse. For example, you might bind the PrintScrn key to all the widgets of an application, so that it prints the screen no matter what widget gets that key. To bind an event at the application level, call the .bind_all() method on any widget (see Section 25, Universal widget methods (p. 93)). Here's how you might bind the PrintScrn key, whose key name is "Print": self.bind_all ( "<Key-Print>", self.__printScreen )
108
Tkinter reference
For keys on the keyboard, this is either the key's character (for single-character keys like the A or * key) or the key's name; see Section 30.5, Key names (p. 110) for a list of all key names. Here are some examples to give you the flavor of event patterns: <Button-1> <KeyPress-H> The user pressed the first mouse button. The user pressed the H key.
Button
ButtonRelease The user let up on a mouse button. This is probably a better choice in most cases than the Button event, because if the user accidentally presses the button, they can move the mouse off the widget to avoid setting off the event. Configure Deactivate The user changed the size of a widget, for example by dragging a corner or side of the window. A widget is changing from being active to being inactive. This refers to changes in the state option of a widget such as a radiobutton changing from active to inactive (grayed out). A widget is being destroyed. The user moved the mouse pointer into a visible part of a widget. (This is different than the enter key, which is a KeyPress event for a key whose name is actually "return".) This event occurs whenever at least some part of your application or widget becomes visible after having been covered up by another window. A widget got the input focus (see Section 29, Focus: routing keyboard input (p. 106) for a general introduction to input focus.) This can happen either in response to a user event (like using the tab key to move focus between widgets) or programmatically (for example, your program calls the .focus_set() on a widget). The input focus was moved out of a widget. As with FocusIn, the user can cause this event, or your program can cause it. The user pressed a key on the keyboard. The detail part specifies which key. This keyword may be abbreviated Key.
22 37
17 7
Destroy Enter
12 9
Expose FocusIn
10 2
FocusOut KeyPress
Tkinter reference
109
Description The user let up on a key. The user moved the mouse pointer out of a widget. A widget is being mapped, that is, made visible in the application. This will happen, for example, when you call the widget's .grid() method. The user moved the mouse pointer entirely within a widget. The user moved the mouse wheel up or down. At present, this binding works on Windows and MacOS, but not under Linux. For Windows and MacOS, see the discussion of the .delta field of the Event instance in Section 30.6, Writing your handler: The Event class (p. 113). For Linux, see the note above under Button. A widget is being unmapped and is no longer visible. This happens, for example, when you use the widget's .grid_remove() method. Happens when at least some part of the application window becomes visible on the screen.
18 15
Unmap Visibility
Control True when the user is holding the control key down. Double Lock Shift Triple
You can use shorter forms of the events. Here are some examples: "<1>" is the same as "<Button-1>". "x" is the same as "<KeyPress-x>". Note that you can leave out the enclosing "<>" for most single-character keypresses, but you can't do that for the space character (whose name is "<space>") or the less-than (<) character (whose name is "<less>").
110
Tkinter reference
The .keysym column shows the key symbol, a string name for the key. This corresponds to the .keysym attribute of the Event object. The .keycode column is the key code. This identifies which key was pressed, but the code does not reflect the state of various modifiers like the shift and control keys and the NumLock key. So, for example, both a and A have the same key code. The .keysym_num column shows a numeric code equivalent to the key symbol. Unlike .keycode, these codes are different for different modifiers. For example, the digit 2 on the numeric keypad (key symbol KP_2) and the down arrow on the numeric keypad (key symbol KP_Down) have the same key code (88), but different .keysym_num values (65433 and 65458, respectively). The Key column shows the text you will usually find on the physical key, such as tab. There are many more key names for international character sets. This table shows only the Latin-1 set for the usual USA-type 101-key keyboard. For the currently supported set, see the manual page for Tk keysym values11. .keysym Alt_L Alt_R BackSpace Cancel Caps_Lock Control_L Control_R Delete Down End Escape Execute F1 F2 Fi F12 Home Insert Left Linefeed KP_0 KP_1 KP_2 KP_3 .keycode .keysym_num Key 64 113 22 110 66 37 109 107 104 103 9 111 67 68 66+i 96 97 106 100 54 90 87 88 89 65513 65514 65288 65387 65549 65507 65508 65535 65364 65367 65307 65378 65470 65471 65469+i 65481 65360 65379 65361 106 65438 65436 65433 65435 The left-hand alt key The right-hand alt key backspace break CapsLock The left-hand control key The right-hand control key Delete end esc SysReq Function key F1 Function key F2 Function key Fi Function key F12 home insert Linefeed (control-J) 0 on the keypad 1 on the keypad 2 on the keypad 3 on the keypad
11
http://www.tcl.tk/man/tcl8.4/TkCmd/keysyms.htm
Tkinter reference
111
.keysym KP_4 KP_5 KP_6 KP_7 KP_8 KP_9 KP_Add KP_Begin KP_Decimal KP_Delete KP_Divide KP_Down KP_End KP_Enter KP_Home KP_Insert KP_Left KP_Next KP_Prior KP_Right KP_Up Next Num_Lock Pause Print Prior Return
.keycode .keysym_num Key 83 84 85 79 80 81 86 84 91 91 112 88 87 108 79 90 83 89 81 85 80 105 77 110 111 99 36 65430 65437 65432 65429 65431 65434 65451 65437 65439 65439 65455 65433 65436 65421 65429 65438 65430 65450 65435 65434 65432 65453 65431 65366 65407 65299 65377 65365 65293 4 on the keypad 5 on the keypad 6 on the keypad 7 on the keypad 8 on the keypad 9 on the keypad + on the keypad The center key (same key as 5) on the keypad Decimal (.) on the keypad delete on the keypad / on the keypad on the keypad end on the keypad enter on the keypad home on the keypad insert on the keypad on the keypad on the keypad PageDown on the keypad PageUp on the keypad on the keypad - on the keypad on the keypad PageDown NumLock pause PrintScrn PageUp The enter key (control-M). The name Enter refers to a mouse-related event, not a keypress; see Section 30, Events (p. 107) ScrollLock The left-hand shift key The right-hand shift key The tab key
KP_Multiply 63
KP_Subtract 82
102 50 62 23 98
Scroll_Lock 78
112
Tkinter reference
.delta
.height .keycode
.keysym
.keysym_num For KeyPress or KeyRelease events, this is set to a numeric version of the .keysym field. For regular keys that produce a single character, this field is set to the integer value of the key's ASCII code. For special keys, refer to Section 30.5, Key names (p. 110). .num If the event was related to a mouse button, this attribute is set to the button number (1, 2, or 3). For mouse wheel support under Linux, bind Button-4 and Button-5 events; when the mouse wheel is scrolled up, this field will be 4, or 5 when scrolled down. An integer serial number that is incremented every time the server processes a client request. You can use .serial values to find the exact time sequence of events: those with lower values happened sooner. An integer describing the state of all the modifier keys. See the table of modifier masks below for the interpretation of this value. This attribute is set to an integer which has no absolute meaning, but is incremented every millisecond. This allows your application to determine, for example, the length of time between two mouse clicks.
.serial
.state .time
Tkinter reference
113
A numeric code describing the type of event. For the interpretation of this code, see Section 30.3, Event types (p. 109). Always set to the widget that caused the event. For example, if the event was a mouse click that happened on a canvas, this attribute will be the actual Canvas widget. If the event was a Configure, this attribute is set to the widget's new width in pixels. The x coordinate of the mouse at the time of the event, relative to the upper left corner of the widget. The y coordinate of the mouse at the time of the event, relative to the upper left corner of the widget. The x coordinate of the mouse at the time of the event, relative to the upper left corner of the screen. The y coordinate of the mouse at the time of the event, relative to the upper left corner of the screen.
Use these masks to test the bits of the .state value to see what modifier keys and buttons were pressed during the event: Mask Modifier
0x0001 Shift. 0x0002 Caps Lock. 0x0004 Control. 0x0008 Left-hand Alt. 0x0010 Num Lock. 0x0080 Right-hand Alt. 0x0100 Mouse button 1. 0x0200 Mouse button 2. 0x0400 Mouse button 3. Here's an example of an event handler. Under Section 30.1, Levels of binding (p. 107), above, there is an example showing how to bind mouse button 2 clicks on a canvas named self.canv to a handler called self.__drawOrangeBlob(). Here is that handler: def __drawOrangeBlob ( self, event ): "Draws an orange blob in self.canv where the mouse is." r = 5 # Blob radius self.canv.create_oval ( event.x-r, event.y-r, event.x+r, event.y+r, fill="orange" ) When this handler is called, the current mouse position is (event.x, event.y). The .create_oval() method draws a circle whose bounding box is square and centered on that position and has sides of length 2*r.
114
Tkinter reference
Suppose further that you want to write one handler named .__cbHandler for <Button-1> events in all ten of these checkbuttons. The handler can get the actual Checkbutton widget that triggered it by referring to the .widget attribute of the Event object that gets passed in, but how does it find out that checkbutton's index in self.cbList? It would be nice to write our handler with an extra argument for the checkbutton number, something like this: def __cbHandler ( self, event, cbNumber ): But event handlers are passed only one argument, the event. So we can't use the function above because of a mismatch in the number of arguments. Fortunately, Python's ability to provide default values for function arguments gives us a way out. Have a look at this code: def __createWidgets ( self ): self.cbList = [] # Create the checkbutton list for i in range(10): cb = Checkbutton ( self, ) self.cbList.append ( cb ) cb.grid( row=1, column=i ) 1 def handler ( event, self=self, i=i ): return self.__cbHandler ( event, i ) cb.bind ( "<Button-1>", handler ) def __cbHandler ( self, event, cbNumber ):
1
These lines define a new function handler that expects three arguments. The first argument is the Event object passed to all event handlers, and the second and third arguments will be set to their default valuesthe extra arguments we need to pass it.
This technique can be extended to supply any number of additional arguments to handlers.
Tkinter reference
115
In each case, the title is a string to be displayed in the top of the window decoration. The message argument is a string that appears in the body of the pop-up window; within this string, lines are broken at newline ("\n") characters. The option arguments may be any of these choices.
116
Tkinter reference
default Which button should be the default choice? If you do not specify this option, the first button (OK, Yes, or Retry) will be the default choice. To specify whith button is the default choice, use default=C, where C is one of these constants defined in tkMessageBox: CANCEL, IGNORE, OK, NO, RETRY, or YES. icon Selects which icon appears in the pop-up. Use an argument of the form icon=I where I is one of these constants defined in tkMessageBox: ERROR, INFO, QUESTION, or WARNING. parent If you don't specify this option, the pop-up appears above your root window. To make the pop-up appear above some child window W, use the argument parent=W. Each of the ask... pop-up functions returns a value that depends on which button the user pushed to remove the pop-up. askokcancel, askretrycancel, and askyesno all return a bool value: True for OK or Yes choices, False for No or Cancel choices. askquestion returns u"yes" for Yes, or u"no" for No.
Tkinter reference
117
parent=W To make the pop-up appear over some window W, supply this argument. The default behavior is that the pop-up will appear over your application's root window. title=T If specified, T is a string to be displayed as the pop-up window's title. If the user selects a file, the returned value is the complete path name of the selected file. If the user uses the Cancel button, the function returns an empty string. Here is an example:
118
Tkinter reference