• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`ttk` --- Tk themed widgets
2================================
3
4.. module:: ttk
5   :synopsis: Tk themed widget set
6.. sectionauthor:: Guilherme Polo <ggpolo@gmail.com>
7
8
9.. index:: single: ttk
10
11The :mod:`ttk` module provides access to the Tk themed widget set, which has
12been introduced in Tk 8.5. If Python is not compiled against Tk 8.5 code may
13still use this module as long as Tile is installed. However, some features
14provided by the new Tk, like anti-aliased font rendering under X11, window
15transparency (on X11 you will need a composition window manager) will be
16missing.
17
18The basic idea of :mod:`ttk` is to separate, to the extent possible, the code
19implementing a widget's behavior from the code implementing its appearance.
20
21
22.. seealso::
23
24   `Tk Widget Styling Support <https://www.tcl.tk/cgi-bin/tct/tip/48>`_
25      The document which brought up theming support for Tk
26
27
28Using Ttk
29---------
30
31To start using Ttk, import its module::
32
33   import ttk
34
35But code like this::
36
37   from Tkinter import *
38
39may optionally want to use this::
40
41   from Tkinter import *
42   from ttk import *
43
44And 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`
47and :class:`Scrollbar`) will automatically substitute for the Tk widgets.
48
49This has the direct benefit of using the new widgets, giving better look & feel
50across platforms, but be aware that they are not totally compatible. The main
51difference is that widget options such as "fg", "bg" and others related to
52widget styling are no longer present in Ttk widgets. Use :class:`ttk.Style` to
53achieve the same (or better) styling.
54
55.. seealso::
56
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.
60
61
62Ttk Widgets
63-----------
64
65Ttk 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
72subclasses of :class:`Widget`.
73
74As said previously, you will notice changes in look-and-feel as well in the
75styling code. To demonstrate the latter, a very simple example is shown below.
76
77Tk code::
78
79   l1 = Tkinter.Label(text="Test", fg="black", bg="white")
80   l2 = Tkinter.Label(text="Test", fg="black", bg="white")
81
82
83Corresponding Ttk code::
84
85   style = ttk.Style()
86   style.configure("BW.TLabel", foreground="black", background="white")
87
88   l1 = ttk.Label(text="Test", style="BW.TLabel")
89   l2 = ttk.Label(text="Test", style="BW.TLabel")
90
91For more information about TtkStyling_ read the :class:`Style` class
92documentation.
93
94Widget
95------
96
97:class:`ttk.Widget` defines standard options and methods supported by Tk
98themed widgets and is not supposed to be directly instantiated.
99
100
101Standard Options
102^^^^^^^^^^^^^^^^
103
104All the :mod:`ttk` widgets accept the following options:
105
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   +-----------+--------------------------------------------------------------+
130
131
132Scrollable Widget Options
133^^^^^^^^^^^^^^^^^^^^^^^^^
134
135The following options are supported by widgets that are controlled by a
136scrollbar.
137
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   +----------------+---------------------------------------------------------+
155
156
157Label Options
158^^^^^^^^^^^^^
159
160The following options are supported by labels, buttons and other button-like
161widgets.
162
163.. tabularcolumns:: |p{0.2\textwidth}|p{0.7\textwidth}|
164..
165
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   +--------------+-----------------------------------------------------------+
202
203
204Compatibility Options
205^^^^^^^^^^^^^^^^^^^^^
206
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   +--------+----------------------------------------------------------------+
215
216Widget States
217^^^^^^^^^^^^^
218
219The widget state is a bitmap of independent state flags.
220
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   +------------+-------------------------------------------------------------+
247
248A state specification is a sequence of state names, optionally prefixed with
249an exclamation point indicating that the bit is off.
250
251
252ttk.Widget
253^^^^^^^^^^
254
255Besides the methods described below, the :class:`ttk.Widget` class supports the
256:meth:`Tkinter.Widget.cget` and :meth:`Tkinter.Widget.configure` methods.
257
258.. class:: Widget
259
260   .. method:: identify(x, y)
261
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.
264
265      *x* and *y* are pixel coordinates relative to the widget.
266
267
268   .. method:: instate(statespec, callback=None, *args, **kw)
269
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*.
274
275
276   .. method:: state([statespec=None])
277
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.
282
283   *statespec* will usually be a list or a tuple.
284
285
286Combobox
287--------
288
289The :class:`ttk.Combobox` widget combines a text field with a pop-down list of
290values. This widget is a subclass of :class:`Entry`.
291
292Besides the methods inherited from :class:`Widget` (:meth:`Widget.cget`,
293:meth:`Widget.configure`, :meth:`Widget.identify`, :meth:`Widget.instate`
294and :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.insert`, :meth:`Entry.selection`,
297:meth:`Entry.xview`), this class has some other methods, described at
298:class:`ttk.Combobox`.
299
300
301Options
302^^^^^^^
303
304This widget accepts the following options:
305
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   +-----------------+--------------------------------------------------------+
342
343
344Virtual events
345^^^^^^^^^^^^^^
346
347The combobox widget generates a **<<ComboboxSelected>>** virtual event
348when the user selects an element from the list of values.
349
350
351ttk.Combobox
352^^^^^^^^^^^^
353
354.. class:: Combobox
355
356   .. method:: current([newindex=None])
357
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.
361
362
363   .. method:: get()
364
365      Returns the current value of the combobox.
366
367
368   .. method:: set(value)
369
370      Sets the value of the combobox to *value*.
371
372
373Notebook
374--------
375
376The Ttk Notebook widget manages a collection of windows and displays a single
377one at a time. Each child window is associated with a tab, which the user
378may select to change the currently-displayed window.
379
380
381Options
382^^^^^^^
383
384This widget accepts the following specific options:
385
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   +---------+----------------------------------------------------------------+
403
404
405Tab Options
406^^^^^^^^^^^
407
408There are also specific options for tabs:
409
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   +-----------+--------------------------------------------------------------+
441
442
443Tab Identifiers
444^^^^^^^^^^^^^^^
445
446The *tab_id* present in several methods of :class:`ttk.Notebook` may take any
447of the following forms:
448
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`).
455
456
457Virtual Events
458^^^^^^^^^^^^^^
459
460This widget generates a **<<NotebookTabChanged>>** virtual event after a new
461tab is selected.
462
463
464ttk.Notebook
465^^^^^^^^^^^^
466
467.. class:: Notebook
468
469   .. method:: add(child, **kw)
470
471      Adds a new tab to the notebook.
472
473      If window is currently managed by the notebook but hidden, it is
474      restored to its previous position.
475
476      See `Tab Options`_ for the list of available options.
477
478
479   .. method:: forget(tab_id)
480
481      Removes the tab specified by *tab_id*, unmaps and unmanages the
482      associated window.
483
484
485   .. method:: hide(tab_id)
486
487      Hides the tab specified by *tab_id*.
488
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.
492
493
494   .. method:: identify(x, y)
495
496      Returns the name of the tab element at position *x*, *y*, or the empty
497      string if none.
498
499
500   .. method:: index(tab_id)
501
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".
504
505
506   .. method:: insert(pos, child, **kw)
507
508      Inserts a pane at the specified position.
509
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.
513
514      See `Tab Options`_ for the list of available options.
515
516
517   .. method:: select([tab_id])
518
519      Selects the specified *tab_id*.
520
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.
524
525
526   .. method:: tab(tab_id, option=None, **kw)
527
528      Query or modify the options of the specific *tab_id*.
529
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.
533
534
535   .. method:: tabs()
536
537      Returns a list of windows managed by the notebook.
538
539
540   .. method:: enable_traversal()
541
542      Enable keyboard traversal for a toplevel window containing this notebook.
543
544      This will extend the bindings for the toplevel window containing the
545      notebook as follows:
546
547      * :kbd:`Control-Tab`: selects the tab following the currently selected one.
548      * :kbd:`Shift-Control-Tab`: selects the tab preceding the currently selected one.
549      * :kbd:`Alt-K`: where *K* is the mnemonic (underlined) character of any tab, will
550        select that tab.
551
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.
555
556
557Progressbar
558-----------
559
560The :class:`ttk.Progressbar` widget shows the status of a long-running
561operation. It can operate in two modes: determinate mode shows the amount
562completed relative to the total amount of work to be done, and indeterminate
563mode provides an animated display to let the user know that something is
564happening.
565
566
567Options
568^^^^^^^
569
570This widget accepts the following specific options:
571
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   +----------+---------------------------------------------------------------+
600
601
602ttk.Progressbar
603^^^^^^^^^^^^^^^
604
605.. class:: Progressbar
606
607   .. method:: start([interval])
608
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.
612
613
614   .. method:: step([amount])
615
616      Increments the progress bar's value by *amount*.
617
618      *amount* defaults to 1.0 if omitted.
619
620
621   .. method:: stop()
622
623      Stop autoincrement mode: cancels any recurring timer event initiated by
624      :meth:`Progressbar.start` for this progress bar.
625
626
627Separator
628---------
629
630The :class:`ttk.Separator` widget displays a horizontal or vertical separator
631bar.
632
633It has no other methods besides the ones inherited from :class:`ttk.Widget`.
634
635
636Options
637^^^^^^^
638
639This widget accepts the following specific option:
640
641   +--------+----------------------------------------------------------------+
642   | option | description                                                    |
643   +========+================================================================+
644   | orient | One of "horizontal" or "vertical". Specifies the orientation of|
645   |        | the separator.                                                 |
646   +--------+----------------------------------------------------------------+
647
648
649Sizegrip
650--------
651
652The :class:`ttk.Sizegrip` widget (also known as a grow box) allows the user to
653resize the containing toplevel window by pressing and dragging the grip.
654
655This widget has neither specific options nor specific methods, besides the
656ones inherited from :class:`ttk.Widget`.
657
658
659Platform-specific notes
660^^^^^^^^^^^^^^^^^^^^^^^
661
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.
665
666
667Bugs
668^^^^
669
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.
674
675
676Treeview
677--------
678
679The :class:`ttk.Treeview` widget displays a hierarchical collection of items.
680Each item has a textual label, an optional image, and an optional list of data
681values. The data values are displayed in successive columns after the tree
682label.
683
684The order in which data values are displayed may be controlled by setting
685the widget option ``displaycolumns``. The tree widget can also display column
686headings. Columns may be accessed by number or symbolic names listed in the
687widget option columns. See `Column Identifiers`_.
688
689Each item is identified by a unique name. The widget will generate item IDs
690if they are not supplied by the caller. There is a distinguished root item,
691named ``{}``. The root item itself is not displayed; its children appear at the
692top level of the hierarchy.
693
694Each item also has a list of tags, which can be used to associate event bindings
695with individual items and control the appearance of the item.
696
697The Treeview widget supports horizontal and vertical scrolling, according to
698the options described in `Scrollable Widget Options`_ and the methods
699:meth:`Treeview.xview` and :meth:`Treeview.yview`.
700
701
702Options
703^^^^^^^
704
705This widget accepts the following specific options:
706
707.. tabularcolumns:: |p{0.2\textwidth}|p{0.7\textwidth}|
708..
709
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   +----------------+--------------------------------------------------------+
751
752
753Item Options
754^^^^^^^^^^^^
755
756The following item options may be specified for items in the insert and item
757widget commands.
758
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   +--------+---------------------------------------------------------------+
778
779
780Tag Options
781^^^^^^^^^^^
782
783The following options may be specified on tags:
784
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   +------------+-----------------------------------------------------------+
797
798
799Column Identifiers
800^^^^^^^^^^^^^^^^^^
801
802Column identifiers take any of the following forms:
803
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.
808
809Notes:
810
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.
815
816A data column number is an index into an item's option values list; a display
817column number is the column number in the tree where the values are displayed.
818Tree labels are displayed in column #0. If option displaycolumns is not set,
819then data column n is displayed in column #n+1. Again, **column #0 always
820refers to the tree column**.
821
822
823Virtual Events
824^^^^^^^^^^^^^^
825
826The Treeview widget generates the following virtual events.
827
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   +--------------------+--------------------------------------------------+
839
840The :meth:`Treeview.focus` and :meth:`Treeview.selection` methods can be used
841to determine the affected item or items.
842
843
844ttk.Treeview
845^^^^^^^^^^^^
846
847.. class:: Treeview
848
849   .. method:: bbox(item, column=None)
850
851      Returns the bounding box (relative to the treeview widget's window) of
852      the specified *item* in the form (x, y, width, height).
853
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.
857
858
859   .. method:: get_children([item])
860
861      Returns the list of children belonging to *item*.
862
863      If *item* is not specified, returns root children.
864
865
866   .. method:: set_children(item, *newchildren)
867
868      Replaces *item*'s child with *newchildren*.
869
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.
874
875
876   .. method:: column(column, option=None, **kw)
877
878      Query or modify the options for the specified *column*.
879
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.
883
884      The valid options/values are:
885
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.
900
901      To configure the tree column, call this with column = "#0"
902
903   .. method:: delete(*items)
904
905      Delete all specified *items* and all their descendants.
906
907      The root item may not be deleted.
908
909
910   .. method:: detach(*items)
911
912      Unlinks all of the specified *items* from the tree.
913
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.
916
917      The root item may not be detached.
918
919
920   .. method:: exists(item)
921
922      Returns ``True`` if the specified *item* is present in the tree.
923
924
925   .. method:: focus([item=None])
926
927      If *item* is specified, sets the focus item to *item*. Otherwise, returns
928      the current focus item, or '' if there is none.
929
930
931   .. method:: heading(column, option=None, **kw)
932
933      Query or modify the heading options for the specified *column*.
934
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.
938
939      The valid options/values are:
940
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.
950
951      To configure the tree column heading, call this with column = "#0".
952
953
954   .. method:: identify(component, x, y)
955
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.
959
960
961   .. method:: identify_row(y)
962
963      Returns the item ID of the item at position *y*.
964
965
966   .. method:: identify_column(x)
967
968      Returns the data column identifier of the cell at position *x*.
969
970      The tree column has ID #0.
971
972
973   .. method:: identify_region(x, y)
974
975      Returns one of:
976
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      +-----------+--------------------------------------+
988
989      Availability: Tk 8.6.
990
991
992   .. method:: identify_element(x, y)
993
994      Returns the element at position *x*, *y*.
995
996      Availability: Tk 8.6.
997
998
999   .. method:: index(item)
1000
1001      Returns the integer index of *item* within its parent's list of children.
1002
1003
1004   .. method:: insert(parent, index, iid=None, **kw)
1005
1006      Creates a new item and returns the item identifier of the newly created
1007      item.
1008
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.
1017
1018      See `Item Options`_ for the list of available points.
1019
1020
1021   .. method:: item(item[, option[, **kw]])
1022
1023      Query or modify the options for the specified *item*.
1024
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*.
1029
1030
1031   .. method:: move(item, parent, index)
1032
1033      Moves *item* to position *index* in *parent*'s list of children.
1034
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.
1039
1040
1041   .. method:: next(item)
1042
1043      Returns the identifier of *item*'s next sibling, or '' if *item* is the
1044      last child of its parent.
1045
1046
1047   .. method:: parent(item)
1048
1049      Returns the ID of the parent of *item*, or '' if *item* is at the top
1050      level of the hierarchy.
1051
1052
1053   .. method:: prev(item)
1054
1055      Returns the identifier of *item*'s previous sibling, or '' if *item* is
1056      the first child of its parent.
1057
1058
1059   .. method:: reattach(item, parent, index)
1060
1061      An alias for :meth:`Treeview.move`.
1062
1063
1064   .. method:: see(item)
1065
1066      Ensure that *item* is visible.
1067
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.
1071
1072
1073   .. method:: selection([selop=None[, items=None]])
1074
1075      If *selop* is not specified, returns selected items. Otherwise, it will
1076      act according to the following selection methods.
1077
1078
1079   .. method:: selection_set(items)
1080
1081      *items* becomes the new selection.
1082
1083
1084   .. method:: selection_add(items)
1085
1086      Add *items* to the selection.
1087
1088
1089   .. method:: selection_remove(items)
1090
1091      Remove *items* from the selection.
1092
1093
1094   .. method:: selection_toggle(items)
1095
1096      Toggle the selection state of each item in *items*.
1097
1098
1099   .. method:: set(item, column=None, value=None)
1100
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*.
1105
1106
1107   .. method:: tag_bind(tagname, sequence=None, callback=None)
1108
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.
1112
1113
1114   .. method:: tag_configure(tagname, option=None, **kw)
1115
1116      Query or modify the options for the specified *tagname*.
1117
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*.
1122
1123
1124   .. method:: tag_has(tagname[, item])
1125
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.
1129
1130      Availability: Tk 8.6
1131
1132
1133   .. method:: xview(*args)
1134
1135      Query or modify horizontal position of the treeview.
1136
1137
1138   .. method:: yview(*args)
1139
1140      Query or modify vertical position of the treeview.
1141
1142
1143.. _TtkStyling:
1144
1145Ttk Styling
1146-----------
1147
1148Each widget in :mod:`ttk` is assigned a style, which specifies the set of
1149elements making up the widget and how they are arranged, along with dynamic and
1150default settings for element options. By default the style name is the same as
1151the widget's class name, but it may be overridden by the widget's style
1152option. If the class name of a widget is unknown, use the method
1153:meth:`Misc.winfo_class` (somewidget.winfo_class()).
1154
1155.. seealso::
1156
1157   `Tcl'2004 conference presentation <http://tktable.sourceforge.net/tile/tile-tcl2004.pdf>`_
1158      This document explains how the theme engine works
1159
1160
1161.. class:: Style
1162
1163   This class is used to manipulate the style database.
1164
1165
1166   .. method:: configure(style, query_opt=None, **kw)
1167
1168      Query or set the default value of the specified option(s) in *style*.
1169
1170      Each key in *kw* is an option and each value is a string identifying
1171      the value for that option.
1172
1173      For example, to change every default button to be a flat button with some
1174      padding and a different background color do::
1175
1176         import ttk
1177         import Tkinter
1178
1179         root = Tkinter.Tk()
1180
1181         ttk.Style().configure("TButton", padding=6, relief="flat",
1182            background="#ccc")
1183
1184         btn = ttk.Button(text="Sample")
1185         btn.pack()
1186
1187         root.mainloop()
1188
1189
1190   .. method:: map(style, query_opt=None, **kw)
1191
1192      Query or sets dynamic values of the specified option(s) in *style*.
1193
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.
1198
1199      An example::
1200
1201         import Tkinter
1202         import ttk
1203
1204         root = Tkinter.Tk()
1205
1206         style = ttk.Style()
1207         style.map("C.TButton",
1208             foreground=[('pressed', 'red'), ('active', 'blue')],
1209             background=[('pressed', '!disabled', 'black'), ('active', 'white')]
1210             )
1211
1212         colored_btn = ttk.Button(text="Test", style="C.TButton").pack()
1213
1214         root.mainloop()
1215
1216
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.
1222
1223   .. method:: lookup(style, option, state=None, default=None)
1224
1225      Returns the value specified for *option* in *style*.
1226
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.
1230
1231      To check what font a Button uses by default, do::
1232
1233         import ttk
1234
1235         print ttk.Style().lookup("TButton", "font")
1236
1237
1238   .. method:: layout(style, layoutspec=None)
1239
1240      Define the widget layout for given *style*. If *layoutspec* is omitted,
1241      return the layout specification for given style.
1242
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 in `Layouts`_.
1247
1248      To understand the format, see the following example (it is not
1249      intended to do anything useful)::
1250
1251         import ttk
1252         import Tkinter
1253
1254         root = Tkinter.Tk()
1255
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         ])
1267
1268         mbtn = ttk.Menubutton(text='Text')
1269         mbtn.pack()
1270         root.mainloop()
1271
1272
1273   .. method:: element_create(elementname, etype, *args, **kw)
1274
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.
1278
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:
1282
1283       * border=padding
1284          padding is a list of up to four integers, specifying the left, top,
1285          right, and bottom borders, respectively.
1286
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.
1290
1291       * padding=padding
1292          Specifies the element's interior padding. Defaults to border's value
1293          if not specified.
1294
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".
1298
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.
1302
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.
1309
1310
1311   .. method:: element_names()
1312
1313      Returns the list of elements defined in the current theme.
1314
1315
1316   .. method:: element_options(elementname)
1317
1318      Returns the list of *elementname*'s options.
1319
1320
1321   .. method:: theme_create(themename, parent=None, settings=None)
1322
1323      Create a new theme.
1324
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`.
1329
1330
1331   .. method:: theme_settings(themename, settings)
1332
1333      Temporarily sets the current theme to *themename*, apply specified
1334      *settings* and then restore the previous theme.
1335
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.
1341
1342      As an example, let's change the Combobox for the default theme a bit::
1343
1344         import ttk
1345         import Tkinter
1346
1347         root = Tkinter.Tk()
1348
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         })
1362
1363         combo = ttk.Combobox().pack()
1364
1365         root.mainloop()
1366
1367
1368   .. method:: theme_names()
1369
1370      Returns a list of all known themes.
1371
1372
1373   .. method:: theme_use([themename])
1374
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.
1378
1379
1380Layouts
1381^^^^^^^
1382
1383A layout can be just ``None``, if it takes no options, or a dict of
1384options specifying how to arrange the element. The layout mechanism
1385uses a simplified version of the pack geometry manager: given an
1386initial cavity, each element is allocated a parcel. Valid
1387options/values are:
1388
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.
1393
1394 * sticky: nswe
1395    Specifies where the element is placed inside its allocated parcel.
1396
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.
1401
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`_.
1406
1407.. _Layout: `Layouts`_
1408