Add better error reporting for MemoryErrors caused by str->float conversions.
[python.git] / Doc / library / ttk.rst
blobebfdede0a2cdf6b4c2ccea112d8afc4463c9501e
1 :mod:`ttk` --- Tk themed widgets
2 ================================
4 .. module:: ttk
5    :synopsis: Tk themed widget set
6 .. sectionauthor:: Guilherme Polo <ggpolo@gmail.com>
9 .. index:: single: ttk
11 The :mod:`ttk` module provides access to the Tk themed widget set, which has
12 been introduced in Tk 8.5. If Python is not compiled against Tk 8.5 code may
13 still use this module as long as Tile is installed. However, some features
14 provided by the new Tk, like anti-aliased font rendering under X11, window
15 transparency (on X11 you will need a composition window manager) will be
16 missing.
18 The basic idea of :mod:`ttk` is to separate, to the extent possible, the code
19 implementing a widget's behavior from the code implementing its appearance.
22 .. seealso::
24    `Tk Widget Styling Support <http://www.tcl.tk/cgi-bin/tct/tip/48>`_
25       The document which brought up theming support for Tk
28 Using Ttk
29 ---------
31 To start using Ttk, import its module::
33    import ttk
35 But code like this::
37    from Tkinter import *
39 may optionally want to use this::
41    from Tkinter import *
42    from ttk import *
44 And then several :mod:`ttk` widgets (:class:`Button`, :class:`Checkbutton`,
45 :class:`Entry`, :class:`Frame`, :class:`Label`, :class:`LabelFrame`,
46 :class:`Menubutton`, :class:`PanedWindow`, :class:`Radiobutton`, :class:`Scale`
47 and :class:`Scrollbar`) will automatically substitute for the Tk widgets.
49 This has the direct benefit of using the new widgets, giving better look & feel
50 across platforms, but be aware that they are not totally compatible. The main
51 difference is that widget options such as "fg", "bg" and others related to
52 widget styling are no longer present in Ttk widgets. Use :class:`ttk.Style` to
53 achieve the same (or better) styling.
55 .. seealso::
57    `Converting existing applications to use the Tile widgets <http://tktable.sourceforge.net/tile/doc/converting.txt>`_
58      A text which talks in Tcl terms about differences typically found when
59      converting applications to use the new widgets.
62 Ttk Widgets
63 -----------
65 Ttk comes with 17 widgets, 11 of which already exist in Tkinter:
66 :class:`Button`, :class:`Checkbutton`, :class:`Entry`, :class:`Frame`,
67 :class:`Label`, :class:`LabelFrame`, :class:`Menubutton`,
68 :class:`PanedWindow`, :class:`Radiobutton`, :class:`Scale` and
69 :class:`Scrollbar`. The 6 new widget classes are: :class:`Combobox`,
70 :class:`Notebook`, :class:`Progressbar`, :class:`Separator`,
71 :class:`Sizegrip` and :class:`Treeview`.  All of these classes are
72 subclasses of :class:`Widget`.
74 As said previously, you will notice changes in look-and-feel as well in the
75 styling code. To demonstrate the latter, a very simple example is shown below.
77 Tk code::
79    l1 = Tkinter.Label(text="Test", fg="black", bg="white")
80    l2 = Tkinter.Label(text="Test", fg="black", bg="white")
83 Corresponding Ttk code::
85    style = ttk.Style()
86    style.configure("BW.TLabel", foreground="black", background="white")
88    l1 = ttk.Label(text="Test", style="BW.TLabel")
89    l2 = ttk.Label(text="Test", style="BW.TLabel")
91 For more information about TtkStyling_ read the :class:`Style` class
92 documentation.
94 Widget
95 ------
97 :class:`ttk.Widget` defines standard options and methods supported by Tk
98 themed widgets and is not supposed to be directly instantiated.
101 Standard Options
102 ^^^^^^^^^^^^^^^^
104 All the :mod:`ttk` widgets accept the following options:
106    +-----------+--------------------------------------------------------------+
107    | Option    | Description                                                  |
108    +===========+==============================================================+
109    | class     | Specifies the window class. The class is used when querying  |
110    |           | the option database for the window's other options, to       |
111    |           | determine the default bindtags for the window, and to select |
112    |           | the widget's default layout and style. This is a read-only   |
113    |           | option which may only be specified when the window is        |
114    |           | created.                                                     |
115    +-----------+--------------------------------------------------------------+
116    | cursor    | Specifies the mouse cursor to be used for the widget. If set |
117    |           | to the empty string (the default), the cursor is inherited   |
118    |           | from the parent widget.                                      |
119    +-----------+--------------------------------------------------------------+
120    | takefocus | Determines whether the window accepts the focus during       |
121    |           | keyboard traversal. 0, 1 or an empty string is returned.     |
122    |           | If 0, the window should be skipped entirely                  |
123    |           | during keyboard traversal. If 1, the window                  |
124    |           | should receive the input focus as long as it is viewable.    |
125    |           | An empty string means that the traversal scripts make the    |
126    |           | decision about whether or not to focus on the window.        |
127    +-----------+--------------------------------------------------------------+
128    | style     | May be used to specify a custom widget style.                |
129    +-----------+--------------------------------------------------------------+
132 Scrollable Widget Options
133 ^^^^^^^^^^^^^^^^^^^^^^^^^
135 The following options are supported by widgets that are controlled by a
136 scrollbar.
138    +----------------+---------------------------------------------------------+
139    | option         | description                                             |
140    +================+=========================================================+
141    | xscrollcommand | Used to communicate with horizontal scrollbars.         |
142    |                |                                                         |
143    |                | When the view in the widget's window changes, the widget|
144    |                | will generate a Tcl command based on the scrollcommand. |
145    |                |                                                         |
146    |                | Usually this option consists of the                     |
147    |                | :meth:`Scrollbar.set` method of some scrollbar. This    |
148    |                | will cause                                              |
149    |                | the scrollbar to be updated whenever the view in the    |
150    |                | window changes.                                         |
151    +----------------+---------------------------------------------------------+
152    | yscrollcommand | Used to communicate with vertical scrollbars.           |
153    |                | For more information, see above.                        |
154    +----------------+---------------------------------------------------------+
157 Label Options
158 ^^^^^^^^^^^^^
160 The following options are supported by labels, buttons and other button-like
161 widgets.
163 .. tabularcolumns:: |p{0.2\textwidth}|p{0.7\textwidth}|
166    +--------------+-----------------------------------------------------------+
167    | option       | description                                               |
168    +==============+===========================================================+
169    | text         | Specifies a text string to be displayed inside the widget.|
170    +--------------+-----------------------------------------------------------+
171    | textvariable | Specifies a name whose value will be used in place of the |
172    |              | text option resource.                                     |
173    +--------------+-----------------------------------------------------------+
174    | underline    | If set, specifies the index (0-based) of a character to   |
175    |              | underline in the text string. The underline character is  |
176    |              | used for mnemonic activation.                             |
177    +--------------+-----------------------------------------------------------+
178    | image        | Specifies an image to display. This is a list of 1 or more|
179    |              | elements. The first element is the default image name. The|
180    |              | rest of the list is a sequence of statespec/value pairs as|
181    |              | defined by :meth:`Style.map`, specifying different images |
182    |              | to use when the widget is in a particular state or a      |
183    |              | combination of states. All images in the list should have |
184    |              | the same size.                                            |
185    +--------------+-----------------------------------------------------------+
186    | compound     | Specifies how to display the image relative to the text,  |
187    |              | in the case both text and image options are present.      |
188    |              | Valid values are:                                         |
189    |              |                                                           |
190    |              | * text: display text only                                 |
191    |              | * image: display image only                               |
192    |              | * top, bottom, left, right: display image above, below,   |
193    |              |   left of, or right of the text, respectively.            |
194    |              | * none: the default. display the image if present,        |
195    |              |   otherwise the text.                                     |
196    +--------------+-----------------------------------------------------------+
197    | width        | If greater than zero, specifies how much space, in        |
198    |              | character widths, to allocate for the text label; if less |
199    |              | than zero, specifies a minimum width. If zero or          |
200    |              | unspecified, the natural width of the text label is used. |
201    +--------------+-----------------------------------------------------------+
204 Compatibility Options
205 ^^^^^^^^^^^^^^^^^^^^^
207    +--------+----------------------------------------------------------------+
208    | option | description                                                    |
209    +========+================================================================+
210    | state  | May be set to "normal" or "disabled" to control the "disabled" |
211    |        | state bit. This is a write-only option: setting it changes the |
212    |        | widget state, but the :meth:`Widget.state` method does not     |
213    |        | affect this option.                                            |
214    +--------+----------------------------------------------------------------+
216 Widget States
217 ^^^^^^^^^^^^^
219 The widget state is a bitmap of independent state flags.
221    +------------+-------------------------------------------------------------+
222    | flag       | description                                                 |
223    +============+=============================================================+
224    | active     | The mouse cursor is over the widget and pressing a mouse    |
225    |            | button will cause some action to occur.                     |
226    +------------+-------------------------------------------------------------+
227    | disabled   | Widget is disabled under program control.                   |
228    +------------+-------------------------------------------------------------+
229    | focus      | Widget has keyboard focus.                                  |
230    +------------+-------------------------------------------------------------+
231    | pressed    | Widget is being pressed.                                    |
232    +------------+-------------------------------------------------------------+
233    | selected   | "On", "true", or "current" for things like Checkbuttons and |
234    |            | radiobuttons.                                               |
235    +------------+-------------------------------------------------------------+
236    | background | Windows and Mac have a notion of an "active" or foreground  |
237    |            | window. The *background* state is set for widgets in a      |
238    |            | background window, and cleared for those in the foreground  |
239    |            | window.                                                     |
240    +------------+-------------------------------------------------------------+
241    | readonly   | Widget should not allow user modification.                  |
242    +------------+-------------------------------------------------------------+
243    | alternate  | A widget-specific alternate display format.                 |
244    +------------+-------------------------------------------------------------+
245    | invalid    | The widget's value is invalid.                              |
246    +------------+-------------------------------------------------------------+
248 A state specification is a sequence of state names, optionally prefixed with
249 an exclamation point indicating that the bit is off.
252 ttk.Widget
253 ^^^^^^^^^^
255 Besides the methods described below, the :class:`ttk.Widget` class supports the
256 :meth:`Tkinter.Widget.cget` and :meth:`Tkinter.Widget.configure` methods.
258 .. class:: Widget
260    .. method:: identify(x, y)
262       Returns the name of the element at position *x* *y*, or the empty string
263       if the point does not lie within any element.
265       *x* and *y* are pixel coordinates relative to the widget.
268    .. method:: instate(statespec[, callback=None[, *args[, **kw]]])
270       Test the widget's state. If a callback is not specified, returns True
271       if the widget state matches *statespec* and False otherwise. If callback
272       is specified then it is called with *args* if widget state matches
273       *statespec*.
276    .. method:: state([statespec=None])
278       Modify or read widget state. If *statespec* is specified, sets the
279       widget state accordingly and returns a new *statespec* indicating
280       which flags were changed. If *statespec* is not specified, returns
281       the currently-enabled state flags.
283    *statespec* will usually be a list or a tuple.
286 Combobox
287 --------
289 The :class:`ttk.Combobox` widget combines a text field with a pop-down list of
290 values. This widget is a subclass of :class:`Entry`.
292 Besides the methods inherited from :class:`Widget` (:meth:`Widget.cget`,
293 :meth:`Widget.configure`, :meth:`Widget.identify`, :meth:`Widget.instate`
294 and :meth:`Widget.state`) and those inherited from :class:`Entry`
295 (:meth:`Entry.bbox`, :meth:`Entry.delete`, :meth:`Entry.icursor`,
296 :meth:`Entry.index`, :meth:`Entry.inset`, :meth:`Entry.selection`,
297 :meth:`Entry.xview`), this class has some other methods, described at
298 :class:`ttk.Combobox`.
301 Options
302 ^^^^^^^
304 This widget accepts the following options:
306    +-----------------+--------------------------------------------------------+
307    | option          | description                                            |
308    +=================+========================================================+
309    | exportselection | Boolean value. If set, the widget selection is linked  |
310    |                 | to the Window Manager selection (which can be returned |
311    |                 | by invoking :meth:`Misc.selection_get`, for example).  |
312    +-----------------+--------------------------------------------------------+
313    | justify         | Specifies how the text is aligned within the widget.   |
314    |                 | One of "left", "center", or "right".                   |
315    +-----------------+--------------------------------------------------------+
316    | height          | Specifies the height of the pop-down listbox, in rows. |
317    +-----------------+--------------------------------------------------------+
318    | postcommand     | A script (possibly registered with                     |
319    |                 | :meth:`Misc.register`) that                            |
320    |                 | is called immediately before displaying the values. It |
321    |                 | may specify which values to display.                   |
322    +-----------------+--------------------------------------------------------+
323    | state           | One of "normal", "readonly", or "disabled". In the     |
324    |                 | "readonly" state, the value may not be edited directly,|
325    |                 | and the user can only select one of the values from the|
326    |                 | dropdown list. In the "normal" state, the text field is|
327    |                 | directly editable. In the "disabled" state, no         |
328    |                 | interaction is possible.                               |
329    +-----------------+--------------------------------------------------------+
330    | textvariable    | Specifies a name whose value is linked to the widget   |
331    |                 | value. Whenever the value associated with that name    |
332    |                 | changes, the widget value is updated, and vice versa.  |
333    |                 | See :class:`Tkinter.StringVar`.                        |
334    +-----------------+--------------------------------------------------------+
335    | values          | Specifies the list of values to display in the         |
336    |                 | drop-down listbox.                                     |
337    +-----------------+--------------------------------------------------------+
338    | width           | Specifies an integer value indicating the desired width|
339    |                 | of the entry window, in average-size characters of the |
340    |                 | widget's font.                                         |
341    +-----------------+--------------------------------------------------------+
344 Virtual events
345 ^^^^^^^^^^^^^^
347 The combobox widget generates a **<<ComboboxSelected>>** virtual event
348 when the user selects an element from the list of values.
351 ttk.Combobox
352 ^^^^^^^^^^^^
354 .. class:: Combobox
356    .. method:: current([newindex=None])
358       If *newindex* is specified, sets the combobox value to the element
359       position *newindex*. Otherwise, returns the index of the current value or
360       -1 if the current value is not in the values list.
363    .. method:: get()
365       Returns the current value of the combobox.
368    .. method:: set(value)
370       Sets the value of the combobox to *value*.
373 Notebook
374 --------
376 The Ttk Notebook widget manages a collection of windows and displays a single
377 one at a time. Each child window is associated with a tab, which the user
378 may select to change the currently-displayed window.
381 Options
382 ^^^^^^^
384 This widget accepts the following specific options:
386    +---------+----------------------------------------------------------------+
387    | option  | description                                                    |
388    +=========+================================================================+
389    | height  | If present and greater than zero, specifies the desired height |
390    |         | of the pane area (not including internal padding or tabs).     |
391    |         | Otherwise, the maximum height of all panes is used.            |
392    +---------+----------------------------------------------------------------+
393    | padding | Specifies the amount of extra space to add around the outside  |
394    |         | of the notebook. The padding is a list of up to four length    |
395    |         | specifications: left top right bottom. If fewer than four      |
396    |         | elements are specified, bottom defaults to top, right defaults |
397    |         | to left, and top defaults to left.                             |
398    +---------+----------------------------------------------------------------+
399    | width   | If present and greater than zero, specifies the desired width  |
400    |         | of the pane area (not including internal padding). Otherwise,  |
401    |         | the maximum width of all panes is used.                        |
402    +---------+----------------------------------------------------------------+
405 Tab Options
406 ^^^^^^^^^^^
408 There are also specific options for tabs:
410    +-----------+--------------------------------------------------------------+
411    | option    | description                                                  |
412    +===========+==============================================================+
413    | state     | Either "normal", "disabled" or "hidden". If "disabled", then |
414    |           | the tab is not selectable. If "hidden", then the tab is not  |
415    |           | shown.                                                       |
416    +-----------+--------------------------------------------------------------+
417    | sticky    | Specifies how the child window is positioned within the pane |
418    |           | area. Value is a string containing zero or more of the       |
419    |           | characters "n", "s", "e" or "w". Each letter refers to a     |
420    |           | side (north, south, east or west) that the child window will |
421    |           | stick to, as per the :meth:`grid` geometry manager.          |
422    +-----------+--------------------------------------------------------------+
423    | padding   | Specifies the amount of extra space to add between the       |
424    |           | notebook and this pane. Syntax is the same as for the option |
425    |           | padding used by this widget.                                 |
426    +-----------+--------------------------------------------------------------+
427    | text      | Specifies a text to be displayed in the tab.                 |
428    +-----------+--------------------------------------------------------------+
429    | image     | Specifies an image to display in the tab. See the option     |
430    |           | image described in :class:`Widget`.                          |
431    +-----------+--------------------------------------------------------------+
432    | compound  | Specifies how to display the image relative to the text, in  |
433    |           | the case both text and image options are present. See        |
434    |           | `Label Options`_ for legal values.                           |
435    +-----------+--------------------------------------------------------------+
436    | underline | Specifies the index (0-based) of a character to underline in |
437    |           | the text string. The underlined character is used for        |
438    |           | mnemonic activation if :meth:`Notebook.enable_traversal` is  |
439    |           | called.                                                      |
440    +-----------+--------------------------------------------------------------+
443 Tab Identifiers
444 ^^^^^^^^^^^^^^^
446 The *tab_id* present in several methods of :class:`ttk.Notebook` may take any
447 of the following forms:
449 * An integer between zero and the number of tabs.
450 * The name of a child window.
451 * A positional specification of the form "@x,y", which identifies the tab.
452 * The literal string "current", which identifies the currently-selected tab.
453 * The literal string "end", which returns the number of tabs (only valid for
454   :meth:`Notebook.index`).
457 Virtual Events
458 ^^^^^^^^^^^^^^
460 This widget generates a **<<NotebookTabChanged>>** virtual event after a new
461 tab is selected.
464 ttk.Notebook
465 ^^^^^^^^^^^^
467 .. class:: Notebook
469    .. method:: add(child, **kw)
471       Adds a new tab to the notebook.
473       If window is currently managed by the notebook but hidden, it is
474       restored to its previous position.
476       See `Tab Options`_ for the list of available options.
479    .. method:: forget(tab_id)
481       Removes the tab specified by *tab_id*, unmaps and unmanages the
482       associated window.
485    .. method:: hide(tab_id)
487       Hides the tab specified by *tab_id*.
489       The tab will not be displayed, but the associated window remains
490       managed by the notebook and its configuration remembered. Hidden tabs
491       may be restored with the :meth:`add` command.
494    .. method:: identify(x, y)
496       Returns the name of the tab element at position *x*, *y*, or the empty
497       string if none.
500    .. method:: index(tab_id)
502       Returns the numeric index of the tab specified by *tab_id*, or the total
503       number of tabs if *tab_id* is the string "end".
506    .. method:: insert(pos, child, **kw)
508       Inserts a pane at the specified position.
510       *pos* is either the string "end", an integer index, or the name of a
511       managed child. If *child* is already managed by the notebook, moves it to
512       the specified position.
514       See `Tab Options`_ for the list of available options.
517    .. method:: select([tab_id])
519       Selects the specified *tab_id*.
521       The associated child window will be displayed, and the
522       previously-selected window (if different) is unmapped. If *tab_id* is
523       omitted, returns the widget name of the currently selected pane.
526    .. method:: tab(tab_id[, option=None[, **kw]])
528       Query or modify the options of the specific *tab_id*.
530       If *kw* is not given, returns a dictionary of the tab option values. If
531       *option* is specified, returns the value of that *option*. Otherwise,
532       sets the options to the corresponding values.
535    .. method:: tabs()
537       Returns a list of windows managed by the notebook.
540    .. method:: enable_traversal()
542       Enable keyboard traversal for a toplevel window containing this notebook.
544       This will extend the bindings for the toplevel window containing the
545       notebook as follows:
547       * Control-Tab: selects the tab following the currently selected one.
548       * Shift-Control-Tab: selects the tab preceding the currently selected one.
549       * Alt-K: where K is the mnemonic (underlined) character of any tab, will
550         select that tab.
552       Multiple notebooks in a single toplevel may be enabled for traversal,
553       including nested notebooks. However, notebook traversal only works
554       properly if all panes have the notebook they are in as master.
557 Progressbar
558 -----------
560 The :class:`ttk.Progressbar` widget shows the status of a long-running
561 operation. It can operate in two modes: determinate mode shows the amount
562 completed relative to the total amount of work to be done, and indeterminate
563 mode provides an animated display to let the user know that something is
564 happening.
567 Options
568 ^^^^^^^
570 This widget accepts the following specific options:
572    +----------+---------------------------------------------------------------+
573    | option   | description                                                   |
574    +==========+===============================================================+
575    | orient   | One of "horizontal" or "vertical". Specifies the orientation  |
576    |          | of the progress bar.                                          |
577    +----------+---------------------------------------------------------------+
578    | length   | Specifies the length of the long axis of the progress bar     |
579    |          | (width if horizontal, height if vertical).                    |
580    +----------+---------------------------------------------------------------+
581    | mode     | One of "determinate" or "indeterminate".                      |
582    +----------+---------------------------------------------------------------+
583    | maximum  | A number specifying the maximum value. Defaults to 100.       |
584    +----------+---------------------------------------------------------------+
585    | value    | The current value of the progress bar. In "determinate" mode, |
586    |          | this represents the amount of work completed. In              |
587    |          | "indeterminate" mode, it is interpreted as modulo *maximum*;  |
588    |          | that is, the progress bar completes one "cycle" when its value|
589    |          | increases by *maximum*.                                       |
590    +----------+---------------------------------------------------------------+
591    | variable | A name which is linked to the option value. If specified, the |
592    |          | value of the progress bar is automatically set to the value of|
593    |          | this name whenever the latter is modified.                    |
594    +----------+---------------------------------------------------------------+
595    | phase    | Read-only option. The widget periodically increments the value|
596    |          | of this option whenever its value is greater than 0 and, in   |
597    |          | determinate mode, less than maximum. This option may be used  |
598    |          | by the current theme to provide additional animation effects. |
599    +----------+---------------------------------------------------------------+
602 ttk.Progressbar
603 ^^^^^^^^^^^^^^^
605 .. class:: Progressbar
607    .. method:: start([interval])
609       Begin autoincrement mode: schedules a recurring timer event that calls
610       :meth:`Progressbar.step` every *interval* milliseconds. If omitted,
611       *interval* defaults to 50 milliseconds.
614    .. method:: step([amount])
616       Increments the progress bar's value by *amount*.
618       *amount* defaults to 1.0 if omitted.
621    .. method:: stop()
623       Stop autoincrement mode: cancels any recurring timer event initiated by
624       :meth:`Progressbar.start` for this progress bar.
627 Separator
628 ---------
630 The :class:`ttk.Separator` widget displays a horizontal or vertical separator
631 bar.
633 It has no other methods besides the ones inherited from :class:`ttk.Widget`.
636 Options
637 ^^^^^^^
639 This widget accepts the following specific option:
641    +--------+----------------------------------------------------------------+
642    | option | description                                                    |
643    +========+================================================================+
644    | orient | One of "horizontal" or "vertical". Specifies the orientation of|
645    |        | the separator.                                                 |
646    +--------+----------------------------------------------------------------+
649 Sizegrip
650 --------
652 The :class:`ttk.Sizegrip` widget (also known as a grow box) allows the user to
653 resize the containing toplevel window by pressing and dragging the grip.
655 This widget has neither specific options nor specific methods, besides the
656 ones inherited from :class:`ttk.Widget`.
659 Platform-specific notes
660 ^^^^^^^^^^^^^^^^^^^^^^^
662 * On Mac OS X, toplevel windows automatically include a built-in size grip
663   by default. Adding a :class:`Sizegrip` is harmless, since the built-in
664   grip will just mask the widget.
667 Bugs
668 ^^^^
670 * If the containing toplevel's position was specified relative to the right
671   or bottom of the screen (e.g. ....), the :class:`Sizegrip` widget will
672   not resize the window.
673 * This widget supports only "southeast" resizing.
676 Treeview
677 --------
679 The :class:`ttk.Treeview` widget displays a hierarchical collection of items.
680 Each item has a textual label, an optional image, and an optional list of data
681 values. The data values are displayed in successive columns after the tree
682 label.
684 The order in which data values are displayed may be controlled by setting
685 the widget option ``displaycolumns``. The tree widget can also display column
686 headings. Columns may be accessed by number or symbolic names listed in the
687 widget option columns. See `Column Identifiers`_.
689 Each item is identified by an unique name. The widget will generate item IDs
690 if they are not supplied by the caller. There is a distinguished root item,
691 named ``{}``. The root item itself is not displayed; its children appear at the
692 top level of the hierarchy.
694 Each item also has a list of tags, which can be used to associate event bindings
695 with individual items and control the appearance of the item.
697 The Treeview widget supports horizontal and vertical scrolling, according to
698 the options described in `Scrollable Widget Options`_ and the methods
699 :meth:`Treeview.xview` and :meth:`Treeview.yview`.
702 Options
703 ^^^^^^^
705 This widget accepts the following specific options:
707 .. tabularcolumns:: |p{0.2\textwidth}|p{0.7\textwidth}|
710    +----------------+--------------------------------------------------------+
711    | option         | description                                            |
712    +================+========================================================+
713    | columns        | A list of column identifiers, specifying the number of |
714    |                | columns and their names.                               |
715    +----------------+--------------------------------------------------------+
716    | displaycolumns | A list of column identifiers (either symbolic or       |
717    |                | integer indices) specifying which data columns are     |
718    |                | displayed and the order in which they appear, or the   |
719    |                | string "#all".                                         |
720    +----------------+--------------------------------------------------------+
721    | height         | Specifies the number of rows which should be visible.  |
722    |                | Note: the requested width is determined from the sum   |
723    |                | of the column widths.                                  |
724    +----------------+--------------------------------------------------------+
725    | padding        | Specifies the internal padding for the widget. The     |
726    |                | padding is a list of up to four length specifications. |
727    +----------------+--------------------------------------------------------+
728    | selectmode     | Controls how the built-in class bindings manage the    |
729    |                | selection. One of "extended", "browse" or "none".      |
730    |                | If set to "extended" (the default), multiple items may |
731    |                | be selected. If "browse", only a single item will be   |
732    |                | selected at a time. If "none", the selection will not  |
733    |                | be changed.                                            |
734    |                |                                                        |
735    |                | Note that the application code and tag bindings can set|
736    |                | the selection however they wish, regardless of the     |
737    |                | value  of this option.                                 |
738    +----------------+--------------------------------------------------------+
739    | show           | A list containing zero or more of the following values,|
740    |                | specifying which elements of the tree to display.      |
741    |                |                                                        |
742    |                | * tree: display tree labels in column #0.              |
743    |                | * headings: display the heading row.                   |
744    |                |                                                        |
745    |                | The default is "tree headings", i.e., show all         |
746    |                | elements.                                              |
747    |                |                                                        |
748    |                | **Note**: Column #0 always refers to the tree column,  |
749    |                | even if show="tree" is not specified.                  |
750    +----------------+--------------------------------------------------------+
753 Item Options
754 ^^^^^^^^^^^^
756 The following item options may be specified for items in the insert and item
757 widget commands.
759    +--------+---------------------------------------------------------------+
760    | option | description                                                   |
761    +========+===============================================================+
762    | text   | The textual label to display for the item.                    |
763    +--------+---------------------------------------------------------------+
764    | image  | A Tk Image, displayed to the left of the label.               |
765    +--------+---------------------------------------------------------------+
766    | values | The list of values associated with the item.                  |
767    |        |                                                               |
768    |        | Each item should have the same number of values as the widget |
769    |        | option columns. If there are fewer values than columns, the   |
770    |        | remaining values are assumed empty. If there are more values  |
771    |        | than columns, the extra values are ignored.                   |
772    +--------+---------------------------------------------------------------+
773    | open   | True/False value indicating whether the item's children should|
774    |        | be displayed or hidden.                                       |
775    +--------+---------------------------------------------------------------+
776    | tags   | A list of tags associated with this item.                     |
777    +--------+---------------------------------------------------------------+
780 Tag Options
781 ^^^^^^^^^^^
783 The following options may be specified on tags:
785    +------------+-----------------------------------------------------------+
786    | option     | description                                               |
787    +============+===========================================================+
788    | foreground | Specifies the text foreground color.                      |
789    +------------+-----------------------------------------------------------+
790    | background | Specifies the cell or item background color.              |
791    +------------+-----------------------------------------------------------+
792    | font       | Specifies the font to use when drawing text.              |
793    +------------+-----------------------------------------------------------+
794    | image      | Specifies the item image, in case the item's image option |
795    |            | is empty.                                                 |
796    +------------+-----------------------------------------------------------+
799 Column Identifiers
800 ^^^^^^^^^^^^^^^^^^
802 Column identifiers take any of the following forms:
804 * A symbolic name from the list of columns option.
805 * An integer n, specifying the nth data column.
806 * A string of the form #n, where n is an integer, specifying the nth display
807   column.
809 Notes:
811 * Item's option values may be displayed in a different order than the order
812   in which they are stored.
813 * Column #0 always refers to the tree column, even if show="tree" is not
814   specified.
816 A data column number is an index into an item's option values list; a display
817 column number is the column number in the tree where the values are displayed.
818 Tree labels are displayed in column #0. If option displaycolumns is not set,
819 then data column n is displayed in column #n+1. Again, **column #0 always
820 refers to the tree column**.
823 Virtual Events
824 ^^^^^^^^^^^^^^
826 The Treeview widget generates the following virtual events.
828    +--------------------+--------------------------------------------------+
829    | event              | description                                      |
830    +====================+==================================================+
831    | <<TreeviewSelect>> | Generated whenever the selection changes.        |
832    +--------------------+--------------------------------------------------+
833    | <<TreeviewOpen>>   | Generated just before settings the focus item to |
834    |                    | open=True.                                       |
835    +--------------------+--------------------------------------------------+
836    | <<TreeviewClose>>  | Generated just after setting the focus item to   |
837    |                    | open=False.                                      |
838    +--------------------+--------------------------------------------------+
840 The :meth:`Treeview.focus` and :meth:`Treeview.selection` methods can be used
841 to determine the affected item or items.
844 ttk.Treeview
845 ^^^^^^^^^^^^
847 .. class:: Treeview
849    .. method:: bbox(item[, column=None])
851       Returns the bounding box (relative to the treeview widget's window) of
852       the specified *item* in the form (x, y, width, height).
854       If *column* is specified, returns the bounding box of that cell. If the
855       *item* is not visible (i.e., if it is a descendant of a closed item or is
856       scrolled offscreen), returns an empty string.
859    .. method:: get_children([item])
861       Returns the list of children belonging to *item*.
863       If *item* is not specified, returns root children.
866    .. method:: set_children(item, *newchildren)
868       Replaces *item*'s child with *newchildren*.
870       Children present in *item* that are not present in *newchildren* are
871       detached from the tree. No items in *newchildren* may be an ancestor of
872       *item*. Note that not specifying *newchildren* results in detaching
873       *item*'s children.
876    .. method:: column(column[, option=None[, **kw]])
878       Query or modify the options for the specified *column*.
880       If *kw* is not given, returns a dict of the column option values. If
881       *option* is specified then the value for that *option* is returned.
882       Otherwise, sets the options to the corresponding values.
884       The valid options/values are:
886       * id
887          Returns the column name. This is a read-only option.
888       * anchor: One of the standard Tk anchor values.
889          Specifies how the text in this column should be aligned with respect
890          to the cell.
891       * minwidth: width
892          The minimum width of the column in pixels. The treeview widget will
893          not make the column any smaller than specified by this option when
894          the widget is resized or the user drags a column.
895       * stretch: True/False
896          Specifies whether the column's width should be adjusted when
897          the widget is resized.
898       * width: width
899          The width of the column in pixels.
901       To configure the tree column, call this with column = "#0"
903    .. method:: delete(*items)
905       Delete all specified *items* and all their descendants.
907       The root item may not be deleted.
910    .. method:: detach(*items)
912       Unlinks all of the specified *items* from the tree.
914       The items and all of their descendants are still present, and may be
915       reinserted at another point in the tree, but will not be displayed.
917       The root item may not be detached.
920    .. method:: exists(item)
922       Returns True if the specified *item* is present in the tree.
925    .. method:: focus([item=None])
927       If *item* is specified, sets the focus item to *item*. Otherwise, returns
928       the current focus item, or '' if there is none.
931    .. method:: heading(column[, option=None[, **kw]])
933       Query or modify the heading options for the specified *column*.
935       If *kw* is not given, returns a dict of the heading option values. If
936       *option* is specified then the value for that *option* is returned.
937       Otherwise, sets the options to the corresponding values.
939       The valid options/values are:
941       * text: text
942          The text to display in the column heading.
943       * image: imageName
944          Specifies an image to display to the right of the column heading.
945       * anchor: anchor
946          Specifies how the heading text should be aligned. One of the standard
947          Tk anchor values.
948       * command: callback
949          A callback to be invoked when the heading label is pressed.
951       To configure the tree column heading, call this with column = "#0".
954    .. method:: identify(component, x, y)
956       Returns a description of the specified *component* under the point given
957       by *x* and *y*, or the empty string if no such *component* is present at
958       that position.
961    .. method:: identify_row(y)
963       Returns the item ID of the item at position *y*.
966    .. method:: identify_column(x)
968       Returns the data column identifier of the cell at position *x*.
970       The tree column has ID #0.
973    .. method:: identify_region(x, y)
975       Returns one of:
977       +-----------+--------------------------------------+
978       | region    | meaning                              |
979       +===========+======================================+
980       | heading   | Tree heading area.                   |
981       +-----------+--------------------------------------+
982       | separator | Space between two columns headings.  |
983       +-----------+--------------------------------------+
984       | tree      | The tree area.                       |
985       +-----------+--------------------------------------+
986       | cell      | A data cell.                         |
987       +-----------+--------------------------------------+
989       Availability: Tk 8.6.
992    .. method:: identify_element(x, y)
994       Returns the element at position *x*, *y*.
996       Availability: Tk 8.6.
999    .. method:: index(item)
1001       Returns the integer index of *item* within its parent's list of children.
1004    .. method:: insert(parent, index[, iid=None[, **kw]])
1006       Creates a new item and returns the item identifier of the newly created
1007       item.
1009       *parent* is the item ID of the parent item, or the empty string to create
1010       a new top-level item. *index* is an integer, or the value "end",
1011       specifying where in the list of parent's children to insert the new item.
1012       If *index* is less than or equal to zero, the new node is inserted at
1013       the beginning; if *index* is greater than or equal to the current number
1014       of children, it is inserted at the end. If *iid* is specified, it is used
1015       as the item identifier; *iid* must not already exist in the tree.
1016       Otherwise, a new unique identifier is generated.
1018       See `Item Options`_ for the list of available points.
1021    .. method:: item(item[, option[, **kw]])
1023       Query or modify the options for the specified *item*.
1025       If no options are given, a dict with options/values for the item is
1026       returned.
1027       If *option* is specified then the value for that option is returned.
1028       Otherwise, sets the options to the corresponding values as given by *kw*.
1031    .. method:: move(item, parent, index)
1033       Moves *item* to position *index* in *parent*'s list of children.
1035       It is illegal to move an item under one of its descendants. If *index* is
1036       less than or equal to zero, *item* is moved to the beginning; if greater
1037       than or equal to the number of children, it is moved to the end. If *item*
1038       was detached it is reattached.
1041    .. method:: next(item)
1043       Returns the identifier of *item*'s next sibling, or '' if *item* is the
1044       last child of its parent.
1047    .. method:: parent(item)
1049       Returns the ID of the parent of *item*, or '' if *item* is at the top
1050       level of the hierarchy.
1053    .. method:: prev(item)
1055       Returns the identifier of *item*'s previous sibling, or '' if *item* is
1056       the first child of its parent.
1059    .. method:: reattach(item, parent, index)
1061       An alias for :meth:`Treeview.move`.
1064    .. method:: see(item)
1066       Ensure that *item* is visible.
1068       Sets all of *item*'s ancestors open option to True, and scrolls the
1069       widget if necessary so that *item* is within the visible portion of
1070       the tree.
1073    .. method:: selection([selop=None[, items=None]])
1075       If *selop* is not specified, returns selected items. Otherwise, it will
1076       act according to the following selection methods.
1079    .. method:: selection_set(items)
1081       *items* becomes the new selection.
1084    .. method:: selection_add(items)
1086       Add *items* to the selection.
1089    .. method:: selection_remove(items)
1091       Remove *items* from the selection.
1094    .. method:: selection_toggle(items)
1096       Toggle the selection state of each item in *items*.
1099    .. method:: set(item[, column=None[, value=None]])
1101       With one argument, returns a dictionary of column/value pairs for the
1102       specified *item*. With two arguments, returns the current value of the
1103       specified *column*. With three arguments, sets the value of given
1104       *column* in given *item* to the specified *value*.
1107    .. method:: tag_bind(tagname[, sequence=None[, callback=None]])
1109       Bind a callback for the given event *sequence* to the tag *tagname*.
1110       When an event is delivered to an item, the callbacks for each of the
1111       item's tags option are called.
1114    .. method:: tag_configure(tagname[, option=None[, **kw]])
1116       Query or modify the options for the specified *tagname*.
1118       If *kw* is not given, returns a dict of the option settings for
1119       *tagname*. If *option* is specified, returns the value for that *option*
1120       for the specified *tagname*. Otherwise, sets the options to the
1121       corresponding values for the given *tagname*.
1124    .. method:: tag_has(tagname[, item])
1126       If *item* is specified, returns 1 or 0 depending on whether the specified
1127       *item* has the given *tagname*. Otherwise, returns a list of all items
1128       that have the specified tag.
1130       Availability: Tk 8.6
1133    .. method:: xview(*args)
1135       Query or modify horizontal position of the treeview.
1138    .. method:: yview(*args)
1140       Query or modify vertical position of the treeview.
1143 .. _TtkStyling:
1145 Ttk Styling
1146 -----------
1148 Each widget in :mod:`ttk` is assigned a style, which specifies the set of
1149 elements making up the widget and how they are arranged, along with dynamic and
1150 default settings for element options. By default the style name is the same as
1151 the widget's class name, but it may be overridden by the widget's style
1152 option. If the class name of a widget is unknown, use the method
1153 :meth:`Misc.winfo_class` (somewidget.winfo_class()).
1155 .. seealso::
1157    `Tcl'2004 conference presentation <http://tktable.sourceforge.net/tile/tile-tcl2004.pdf>`_
1158       This document explains how the theme engine works
1161 .. class:: Style
1163    This class is used to manipulate the style database.
1166    .. method:: configure(style, query_opt=None, **kw)
1168       Query or set the default value of the specified option(s) in *style*.
1170       Each key in *kw* is an option and each value is a string identifying
1171       the value for that option.
1173       For example, to change every default button to be a flat button with some
1174       padding and a different background color do::
1176          import ttk
1177          import Tkinter
1179          root = Tkinter.Tk()
1181          ttk.Style().configure("TButton", padding=6, relief="flat",
1182             background="#ccc")
1184          btn = ttk.Button(text="Sample")
1185          btn.pack()
1187          root.mainloop()
1190    .. method:: map(style, query_opt=None, **kw)
1192       Query or sets dynamic values of the specified option(s) in *style*.
1194       Each key in *kw* is an option and each value should be a list or a
1195       tuple (usually) containing statespecs grouped in tuples, lists, or
1196       something else of your preference. A statespec is a compound of one
1197       or more states and then a value.
1199       An example::
1201          import Tkinter
1202          import ttk
1204          root = Tkinter.Tk()
1206          style = ttk.Style()
1207          style.map("C.TButton",
1208              foreground=[('pressed', 'red'), ('active', 'blue')],
1209              background=[('pressed', '!disabled', 'black'), ('active', 'white')]
1210              )
1212          colored_btn = ttk.Button(text="Test", style="C.TButton").pack()
1214          root.mainloop()
1217       Note that the order of the (states, value) sequences for an
1218       option matters.  In the previous example, if you change the
1219       order to ``[('active', 'blue'), ('pressed', 'red')]`` in the
1220       foreground option, for example, you would get a blue foreground
1221       when the widget is in the active or pressed states.
1223    .. method:: lookup(style, option[, state=None[, default=None]])
1225       Returns the value specified for *option* in *style*.
1227       If *state* is specified, it is expected to be a sequence of one or more
1228       states. If the *default* argument is set, it is used as a fallback value
1229       in case no specification for option is found.
1231       To check what font a Button uses by default, do::
1233          import ttk
1235          print ttk.Style().lookup("TButton", "font")
1238    .. method:: layout(style[, layoutspec=None])
1240       Define the widget layout for given *style*. If *layoutspec* is omitted,
1241       return the layout specification for given style.
1243       *layoutspec*, if specified, is expected to be a list or some other
1244       sequence type (excluding strings), where each item should be a tuple and
1245       the first item is the layout name and the second item should have the
1246       format described described in `Layouts`_.
1248       To understand the format, see the following example (it is not
1249       intended to do anything useful)::
1251          import ttk
1252          import Tkinter
1254          root = Tkinter.Tk()
1256          style = ttk.Style()
1257          style.layout("TMenubutton", [
1258             ("Menubutton.background", None),
1259             ("Menubutton.button", {"children":
1260                 [("Menubutton.focus", {"children":
1261                     [("Menubutton.padding", {"children":
1262                         [("Menubutton.label", {"side": "left", "expand": 1})]
1263                     })]
1264                 })]
1265             }),
1266          ])
1268          mbtn = ttk.Menubutton(text='Text')
1269          mbtn.pack()
1270          root.mainloop()
1273    .. method:: element_create(elementname, etype, *args, **kw)
1275       Create a new element in the current theme, of the given *etype* which is
1276       expected to be either "image", "from" or "vsapi". The latter is only
1277       available in Tk 8.6a for Windows XP and Vista and is not described here.
1279       If "image" is used, *args* should contain the default image name followed
1280       by statespec/value pairs (this is the imagespec), and *kw* may have the
1281       following options:
1283        * border=padding
1284           padding is a list of up to four integers, specifying the left, top,
1285           right, and bottom borders, respectively.
1287        * height=height
1288           Specifies a minimum height for the element. If less than zero, the
1289           base image's height is used as a default.
1291        * padding=padding
1292           Specifies the element's interior padding. Defaults to border's value
1293           if not specified.
1295        * sticky=spec
1296           Specifies how the image is placed within the final parcel. spec
1297           contains zero or more characters “n”, “s”, “w”, or “e”.
1299        * width=width
1300           Specifies a minimum width for the element. If less than zero, the
1301           base image's width is used as a default.
1303       If "from" is used as the value of *etype*,
1304       :meth:`element_create` will clone an existing
1305       element. *args* is expected to contain a themename, from which
1306       the element will be cloned, and optionally an element to clone from.
1307       If this element to clone from is not specified, an empty element will
1308       be used. *kw* is discarded.
1311    .. method:: element_names()
1313       Returns the list of elements defined in the current theme.
1316    .. method:: element_options(elementname)
1318       Returns the list of *elementname*'s options.
1321    .. method:: theme_create(themename[, parent=None[, settings=None]])
1323       Create a new theme.
1325       It is an error if *themename* already exists. If *parent* is specified,
1326       the new theme will inherit styles, elements and layouts from the parent
1327       theme. If *settings* are present they are expected to have the same
1328       syntax used for :meth:`theme_settings`.
1331    .. method:: theme_settings(themename, settings)
1333       Temporarily sets the current theme to *themename*, apply specified
1334       *settings* and then restore the previous theme.
1336       Each key in *settings* is a style and each value may contain the keys
1337       'configure', 'map', 'layout' and 'element create' and they are expected
1338       to have the same format as specified by the methods
1339       :meth:`Style.configure`, :meth:`Style.map`, :meth:`Style.layout` and
1340       :meth:`Style.element_create` respectively.
1342       As an example, let's change the Combobox for the default theme a bit::
1344          import ttk
1345          import Tkinter
1347          root = Tkinter.Tk()
1349          style = ttk.Style()
1350          style.theme_settings("default", {
1351             "TCombobox": {
1352                 "configure": {"padding": 5},
1353                 "map": {
1354                     "background": [("active", "green2"),
1355                                    ("!disabled", "green4")],
1356                     "fieldbackground": [("!disabled", "green3")],
1357                     "foreground": [("focus", "OliveDrab1"),
1358                                    ("!disabled", "OliveDrab2")]
1359                 }
1360             }
1361          })
1363          combo = ttk.Combobox().pack()
1365          root.mainloop()
1368    .. method:: theme_names()
1370       Returns a list of all known themes.
1373    .. method:: theme_use([themename])
1375       If *themename* is not given, returns the theme in use.  Otherwise, sets
1376       the current theme to *themename*, refreshes all widgets and emits a
1377       <<ThemeChanged>> event.
1380 Layouts
1381 ^^^^^^^
1383 A layout can be just None, if it takes no options, or a dict of
1384 options specifying how to arrange the element. The layout mechanism
1385 uses a simplified version of the pack geometry manager: given an
1386 initial cavity, each element is allocated a parcel. Valid
1387 options/values are:
1389  * side: whichside
1390     Specifies which side of the cavity to place the element; one of
1391     top, right, bottom or left. If omitted, the element occupies the
1392     entire cavity.
1394  * sticky: nswe
1395     Specifies where the element is placed inside its allocated parcel.
1397  * unit: 0 or 1
1398     If set to 1, causes the element and all of its descendants to be treated as
1399     a single element for the purposes of :meth:`Widget.identify` et al. It's
1400     used for things like scrollbar thumbs with grips.
1402  * children: [sublayout... ]
1403     Specifies a list of elements to place inside the element. Each
1404     element is a tuple (or other sequence type) where the first item is
1405     the layout name, and the other is a `Layout`_.
1407 .. _Layout: `Layouts`_