Source code: Lib/tkinter/ttk.py
The tkinter.ttk module provides access to the Tk themed widget set, introduced in Tk 8.5. If Python has not been compiled against Tk 8.5, this module can still be accessed if Tile has been installed. The former method using Tk 8.5 provides additional benefits including anti-aliased font rendering under X11 and window transparency (requiring a composition window manager on X11).
The basic idea for tkinter.ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance.
See also
A document introducing theming support for Tk
To start using Ttk, import its module:
To override the basic Tk widgets, the import should follow the Tk import:
That code causes several tkinter.ttk widgets (Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar) to automatically replace the Tk widgets.
This has the direct benefit of using the new widgets which gives a better look and feel across platforms; however, the replacement widgets are not completely compatible. The main difference is that widget options such as “fg”, “bg” and others related to widget styling are no longer present in Ttk widgets. Instead, use the ttk.Style class for improved styling effects.
See also
A monograph (using Tcl terminology) about differences typically encountered when moving applications to use the new widgets.
Ttk comes with 18 widgets, twelve of which already existed in tkinter: Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale, Scrollbar, and Spinbox. The other six are new: Combobox, Notebook, Progressbar, Separator, Sizegrip and Treeview. And all them are subclasses of Widget.
Using the Ttk widgets gives the application an improved look and feel. As discussed above, there are differences in how the styling is coded.
Tk code:
Ttk code:
For more information about TtkStyling, see the Style class documentation.
ttk.Widget defines standard options and methods supported by Tk themed widgets and is not supposed to be directly instantiated.
All the ttk Widgets accepts the following options:
Option
Description
class
Specifies the window class. The class is used when querying the option database for the window’s other options, to determine the default bindtags for the window, and to select the widget’s default layout and style. This option is read-only, and may only be specified when the window is created.
cursor
Specifies the mouse cursor to be used for the widget. If set to the empty string (the default), the cursor is inherited for the parent widget.
takefocus
Determines whether the window accepts the focus during keyboard traversal. 0, 1 or an empty string is returned. If 0 is returned, it means that the window should be skipped entirely during keyboard traversal. If 1, it means that the window should receive the input focus as long as it is viewable. And an empty string means that the traversal scripts make the decision about whether or not to focus on the window.
style
May be used to specify a custom widget style.
The following options are supported by widgets that are controlled by a scrollbar.
Option
Description
xscrollcommand
Used to communicate with horizontal scrollbars.
When the view in the widget’s window change, the widget will generate a Tcl command based on the scrollcommand.
Usually this option consists of the method Scrollbar.set() of some scrollbar. This will cause the scrollbar to be updated whenever the view in the window changes.
yscrollcommand
Used to communicate with vertical scrollbars. For some more information, see above.
The following options are supported by labels, buttons and other button-like widgets.
Option
Description
text
Specifies a text string to be displayed inside the widget.
textvariable
Specifies a name whose value will be used in place of the text option resource.
underline
If set, specifies the index (0-based) of a character to underline in the text string. The underline character is used for mnemonic activation.
image
Specifies an image to display. This is a list of 1 or more elements. The first element is the default image name. The rest of the list if a sequence of statespec/value pairs as defined by Style.map(), specifying different images to use when the widget is in a particular state or a combination of states. All images in the list should have the same size.
compound
Specifies how to display the image relative to the text, in the case both text and images options are present. Valid values are:
width
If greater than zero, specifies how much space, in character widths, to allocate for the text label, if less than zero, specifies a minimum width. If zero or unspecified, the natural width of the text label is used.
Option
Description
state
May be set to “normal” or “disabled” to control the “disabled” state bit. This is a write-only option: setting it changes the widget state, but the Widget.state() method does not affect this option.
The widget state is a bitmap of independent state flags.
Flag
Description
active
The mouse cursor is over the widget and pressing a mouse button will cause some action to occur
disabled
Widget is disabled under program control
focus
Widget has keyboard focus
pressed
Widget is being pressed
selected
“On”, “true”, or “current” for things like Checkbuttons and radiobuttons
background
Windows and Mac have a notion of an “active” or foreground window. The background state is set for widgets in a background window, and cleared for those in the foreground window
readonly
Widget should not allow user modification
alternate
A widget-specific alternate display format
invalid
The widget’s value is invalid
A state specification is a sequence of state names, optionally prefixed with an exclamation point indicating that the bit is off.
Besides the methods described below, the ttk.Widget supports the methods tkinter.Widget.cget() and tkinter.Widget.configure().
Returns the name of the element at position x y, or the empty string if the point does not lie within any element.
x and y are pixel coordinates relative to the widget.
Test the widget’s state. If a callback is not specified, returns True if the widget state matches statespec and False otherwise. If callback is specified then it is called with args if widget state matches statespec.
Modify or inquire widget state. If statespec is specified, sets the widget state according to it and return a new statespec indicating which flags were changed. If statespec is not specified, returns the currently-enabled state flags.
statespec will usually be a list or a tuple.
The ttk.Combobox widget combines a text field with a pop-down list of values. This widget is a subclass of Entry.
Besides the methods inherited from Widget: Widget.cget(), Widget.configure(), Widget.identify(), Widget.instate() and Widget.state(), and the following inherited from Entry: Entry.bbox(), Entry.delete(), Entry.icursor(), Entry.index(), Entry.insert(), Entry.selection(), Entry.xview(), it has some other methods, described at ttk.Combobox.
This widget accepts the following specific options:
Option
Description
exportselection
Boolean value. If set, the widget selection is linked to the Window Manager selection (which can be returned by invoking Misc.selection_get, for example).
justify
Specifies how the text is aligned within the widget. One of “left”, “center”, or “right”.
height
Specifies the height of the pop-down listbox, in rows.
postcommand
A script (possibly registered with Misc.register) that is called immediately before displaying the values. It may specify which values to display.
state
One of “normal”, “readonly”, or “disabled”. In the “readonly” state, the value may not be edited directly, and the user can only selection of the values from the dropdown list. In the “normal” state, the text field is directly editable. In the “disabled” state, no interaction is possible.
textvariable
Specifies a name whose value is linked to the widget value. Whenever the value associated with that name changes, the widget value is updated, and vice versa. See tkinter.StringVar.
values
Specifies the list of values to display in the drop-down listbox.
width
Specifies an integer value indicating the desired width of the entry window, in average-size characters of the widget’s font.
The combobox widgets generates a <<ComboboxSelected>> virtual event when the user selects an element from the list of values.
If newindex is specified, sets the combobox value to the element position newindex. Otherwise, returns the index of the current value or -1 if the current value is not in the values list.
Returns the current value of the combobox.
Sets the value of the combobox to value.
The ttk.Spinbox widget is a ttk.Entry enhanced with increment and decrement arrows. It can be used for numbers or lists of string values. This widget is a subclass of Entry.
Besides the methods inherited from Widget: Widget.cget(), Widget.configure(), Widget.identify(), Widget.instate() and Widget.state(), and the following inherited from Entry: Entry.bbox(), Entry.delete(), Entry.icursor(), Entry.index(), Entry.insert(), Entry.xview(), it has some other methods, described at ttk.Spinbox.
This widget accepts the following specific options:
Option
Description
from
Float value. If set, this is the minimum value to which the decrement button will decrement. Must be spelled as from_ when used as an argument, since from is a Python keyword.
to
Float value. If set, this is the maximum value to which the increment button will increment.
increment
Float value. Specifies the amount which the increment/decrement buttons change the value. Defaults to 1.0.
values
Sequence of string or float values. If specified, the increment/decrement buttons will cycle through the items in this sequence rather than incrementing or decrementing numbers.
wrap
Boolean value. If True, increment and decrement buttons will cycle from the to value to the from value or the from value to the to value, respectively.
format
String value. This specifies the format of numbers set by the increment/decrement buttons. It must be in the form “%W.Pf”, where W is the padded width of the value, P is the precision, and ‘%’ and ‘f’ are literal.
command
Python callable. Will be called with no arguments whenever either of the increment or decrement buttons are pressed.
The spinbox widget generates an <<Increment>> virtual event when the user presses <Up>, and a <<Decrement>> virtual event when the user presses <Down>.
Returns the current value of the spinbox.
Sets the value of the spinbox to value.
Ttk Notebook widget manages a collection of windows and displays a single one at a time. Each child window is associated with a tab, which the user may select to change the currently-displayed window.
This widget accepts the following specific options:
Option
Description
height
If present and greater than zero, specifies the desired height of the pane area (not including internal padding or tabs). Otherwise, the maximum height of all panes is used.
padding
Specifies the amount of extra space to add around the outside of the notebook. The padding is a list up to four length specifications left top right bottom. If fewer than four elements are specified, bottom defaults to top, right defaults to left, and top defaults to left.
width
If present and greater than zero, specified the desired width of the pane area (not including internal padding). Otherwise, the maximum width of all panes is used.
There are also specific options for tabs:
Option
Description
state
Either “normal”, “disabled” or “hidden”. If “disabled”, then the tab is not selectable. If “hidden”, then the tab is not shown.
sticky
Specifies how the child window is positioned within the pane area. Value is a string containing zero or more of the characters “n”, “s”, “e” or “w”. Each letter refers to a side (north, south, east or west) that the child window will stick to, as per the grid() geometry manager.
padding
Specifies the amount of extra space to add between the notebook and this pane. Syntax is the same as for the option padding used by this widget.
text
Specifies a text to be displayed in the tab.
image
Specifies an image to display in the tab. See the option image described in Widget.
compound
Specifies how to display the image relative to the text, in the case both options text and image are present. See Label Options for legal values.
underline
Specifies the index (0-based) of a character to underline in the text string. The underlined character is used for mnemonic activation if Notebook.enable_traversal() is called.
The tab_id present in several methods of ttk.Notebook may take any of the following forms:
This widget generates a <<NotebookTabChanged>> virtual event after a new tab is selected.
Adds a new tab to the notebook.
If window is currently managed by the notebook but hidden, it is restored to its previous position.
See Tab Options for the list of available options.
Removes the tab specified by tab_id, unmaps and unmanages the associated window.
Hides the tab specified by tab_id.
The tab will not be displayed, but the associated window remains managed by the notebook and its configuration remembered. Hidden tabs may be restored with the add() command.
Returns the name of the tab element at position x, y, or the empty string if none.
Returns the numeric index of the tab specified by tab_id, or the total number of tabs if tab_id is the string “end”.
Inserts a pane at the specified position.
pos is either the string “end”, an integer index, or the name of a managed child. If child is already managed by the notebook, moves it to the specified position.
See Tab Options for the list of available options.
Selects the specified tab_id.
The associated child window will be displayed, and the previously-selected window (if different) is unmapped. If tab_id is omitted, returns the widget name of the currently selected pane.
Query or modify the options of the specific tab_id.
If kw is not given, returns a dictionary of the tab option values. If option is specified, returns the value of that option. Otherwise, sets the options to the corresponding values.
Returns a list of windows managed by the notebook.
Enable keyboard traversal for a toplevel window containing this notebook.
This will extend the bindings for the toplevel window containing the notebook as follows:
Multiple notebooks in a single toplevel may be enabled for traversal, including nested notebooks. However, notebook traversal only works properly if all panes have the notebook they are in as master.
The ttk.Progressbar widget shows the status of a long-running operation. It can operate in two modes: 1) the determinate mode which shows the amount completed relative to the total amount of work to be done and 2) the indeterminate mode which provides an animated display to let the user know that work is progressing.
This widget accepts the following specific options:
Option
Description
orient
One of “horizontal” or “vertical”. Specifies the orientation of the progress bar.
length
Specifies the length of the long axis of the progress bar (width if horizontal, height if vertical).
mode
One of “determinate” or “indeterminate”.
maximum
A number specifying the maximum value. Defaults to 100.
value
The current value of the progress bar. In “determinate” mode, this represents the amount of work completed. In “indeterminate” mode, it is interpreted as modulo maximum; that is, the progress bar completes one “cycle” when its value increases by maximum.
variable
A name which is linked to the option value. If specified, the value of the progress bar is automatically set to the value of this name whenever the latter is modified.
phase
Read-only option. The widget periodically increments the value of this option whenever its value is greater than 0 and, in determinate mode, less than maximum. This option may be used by the current theme to provide additional animation effects.
Begin autoincrement mode: schedules a recurring timer event that calls Progressbar.step() every interval milliseconds. If omitted, interval defaults to 50 milliseconds.
Increments the progress bar’s value by amount.
amount defaults to 1.0 if omitted.
Stop autoincrement mode: cancels any recurring timer event initiated by Progressbar.start() for this progress bar.
The ttk.Separator widget displays a horizontal or vertical separator bar.
It has no other methods besides the ones inherited from ttk.Widget.
This widget accepts the following specific option:
Option
Description
orient
One of “horizontal” or “vertical”. Specifies the orientation of the separator.
The ttk.Sizegrip widget (also known as a grow box) allows the user to resize the containing toplevel window by pressing and dragging the grip.
This widget has neither specific options nor specific methods, besides the ones inherited from ttk.Widget.
The ttk.Treeview widget displays a hierarchical collection of items. Each item has a textual label, an optional image, and an optional list of data values. The data values are displayed in successive columns after the tree label.
The order in which data values are displayed may be controlled by setting the widget option displaycolumns. The tree widget can also display column headings. Columns may be accessed by number or symbolic names listed in the widget option columns. See Column Identifiers.
Each item is identified by a unique name. The widget will generate item IDs if they are not supplied by the caller. There is a distinguished root item, named {}. The root item itself is not displayed; its children appear at the top level of the hierarchy.
Each item also has a list of tags, which can be used to associate event bindings with individual items and control the appearance of the item.
The Treeview widget supports horizontal and vertical scrolling, according to the options described in Scrollable Widget Options and the methods Treeview.xview() and Treeview.yview().
This widget accepts the following specific options:
Option
Description
columns
A list of column identifiers, specifying the number of columns and their names.
displaycolumns
A list of column identifiers (either symbolic or integer indices) specifying which data columns are displayed and the order in which they appear, or the string “#all”.
height
Specifies the number of rows which should be visible. Note: the requested width is determined from the sum of the column widths.
padding
Specifies the internal padding for the widget. The padding is a list of up to four length specifications.
selectmode
Controls how the built-in class bindings manage the selection. One of “extended”, “browse” or “none”. If set to “extended” (the default), multiple items may be selected. If “browse”, only a single item will be selected at a time. If “none”, the selection will not be changed.
Note that the application code and tag bindings can set the selection however they wish, regardless of the value of this option.
show
A list containing zero or more of the following values, specifying which elements of the tree to display.
The default is “tree headings”, i.e., show all elements.
Note: Column #0 always refers to the tree column, even if show=”tree” is not specified.
The following item options may be specified for items in the insert and item widget commands.
Option
Description
text
The textual label to display for the item.
image
A Tk Image, displayed to the left of the label.
values
The list of values associated with the item.
Each item should have the same number of values as the widget option columns. If there are fewer values than columns, the remaining values are assumed empty. If there are more values than columns, the extra values are ignored.
open
True/False value indicating whether the item’s children should be displayed or hidden.
tags
A list of tags associated with this item.
The following options may be specified on tags:
Option
Description
foreground
Specifies the text foreground color.
background
Specifies the cell or item background color.
font
Specifies the font to use when drawing text.
image
Specifies the item image, in case the item’s image option is empty.
Column identifiers take any of the following forms:
Notes:
A data column number is an index into an item’s option values list; a display column number is the column number in the tree where the values are displayed. Tree labels are displayed in column #0. If option displaycolumns is not set, then data column n is displayed in column #n+1. Again, column #0 always refers to the tree column.
The Treeview widget generates the following virtual events.
Event
Description
<<TreeviewSelect>>
Generated whenever the selection changes.
<<TreeviewOpen>>
Generated just before settings the focus item to open=True.
<<TreeviewClose>>
Generated just after setting the focus item to open=False.
The Treeview.focus() and Treeview.selection() methods can be used to determine the affected item or items.
Returns the bounding box (relative to the treeview widget’s window) of the specified item in the form (x, y, width, height).
If column is specified, returns the bounding box of that cell. If the item is not visible (i.e., if it is a descendant of a closed item or is scrolled offscreen), returns an empty string.
Returns the list of children belonging to item.
If item is not specified, returns root children.
Replaces item’s child with newchildren.
Children present in item that are not present in newchildren are detached from the tree. No items in newchildren may be an ancestor of item. Note that not specifying newchildren results in detaching item’s children.
Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.
The valid options/values are:
Returns the column name. This is a read-only option.
Specifies how the text in this column should be aligned with respect to the cell.
The minimum width of the column in pixels. The treeview widget will not make the column any smaller than specified by this option when the widget is resized or the user drags a column.
Specifies whether the column’s width should be adjusted when the widget is resized.
The width of the column in pixels.
To configure the tree column, call this with column = “#0”
Delete all specified items and all their descendants.
The root item may not be deleted.
Unlinks all of the specified items from the tree.
The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed.
The root item may not be detached.
Returns True if the specified item is present in the tree.
If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or ‘’ if there is none.
Query or modify the heading options for the specified column.
If kw is not given, returns a dict of the heading option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.
The valid options/values are:
The text to display in the column heading.
Specifies an image to display to the right of the column heading.
Specifies how the heading text should be aligned. One of the standard Tk anchor values.
A callback to be invoked when the heading label is pressed.
To configure the tree column heading, call this with column = “#0”.
Returns a description of the specified component under the point given by x and y, or the empty string if no such component is present at that position.
Returns the item ID of the item at position y.
Returns the data column identifier of the cell at position x.
The tree column has ID #0.
Returns one of:
region
meaning
heading
Tree heading area.
separator
Space between two columns headings.
tree
The tree area.
cell
A data cell.
Availability: Tk 8.6.
Returns the element at position x, y.
Availability: Tk 8.6.
Returns the integer index of item within its parent’s list of children.
Creates a new item and returns the item identifier of the newly created item.
parent is the item ID of the parent item, or the empty string to create a new top-level item. index is an integer, or the value “end”, specifying where in the list of parent’s children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning; if index is greater than or equal to the current number of children, it is inserted at the end. If iid is specified, it is used as the item identifier; iid must not already exist in the tree. Otherwise, a new unique identifier is generated.
See Item Options for the list of available points.
Query or modify the options for the specified item.
If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by kw.
Moves item to position index in parent’s list of children.
It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning; if greater than or equal to the number of children, it is moved to the end. If item was detached it is reattached.
Returns the identifier of item’s next sibling, or ‘’ if item is the last child of its parent.
Returns the ID of the parent of item, or ‘’ if item is at the top level of the hierarchy.
Returns the identifier of item’s previous sibling, or ‘’ if item is the first child of its parent.
An alias for Treeview.move().
Ensure that item is visible.
Sets all of item’s ancestors open option to True, and scrolls the widget if necessary so that item is within the visible portion of the tree.
Returns a tuple of selected items.
Changed in version 3.8: selection() no longer takes arguments. For changing the selection state use the following selection methods.
items becomes the new selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
Add items to the selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
Remove items from the selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
Toggle the selection state of each item in items.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
With one argument, returns a dictionary of column/value pairs for the specified item. With two arguments, returns the current value of the specified column. With three arguments, sets the value of given column in given item to the specified value.
Bind a callback for the given event sequence to the tag tagname. When an event is delivered to an item, the callbacks for each of the item’s tags option are called.
Query or modify the options for the specified tagname.
If kw is not given, returns a dict of the option settings for tagname. If option is specified, returns the value for that option for the specified tagname. Otherwise, sets the options to the corresponding values for the given tagname.
If item is specified, returns 1 or 0 depending on whether the specified item has the given tagname. Otherwise, returns a list of all items that have the specified tag.
Availability: Tk 8.6
Query or modify horizontal position of the treeview.
Query or modify vertical position of the treeview.
Each widget in ttk is assigned a style, which specifies the set of elements making up the widget and how they are arranged, along with dynamic and default settings for element options. By default the style name is the same as the widget’s class name, but it may be overridden by the widget’s style option. If you don’t know the class name of a widget, use the method Misc.winfo_class() (somewidget.winfo_class()).
See also
This document explains how the theme engine works
This class is used to manipulate the style database.
Query or set the default value of the specified option(s) in style.
Each key in kw is an option and each value is a string identifying the value for that option.
For example, to change every default button to be a flat button with some padding and a different background color:
Query or sets dynamic values of the specified option(s) in style.
Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, lists, or some other preference. A statespec is a compound of one or more states and then a value.
An example may make it more understandable:
Note that the order of the (states, value) sequences for an option does matter, if the order is changed to [('active', 'blue'), ('pressed',
'red')] in the foreground option, for example, the result would be a blue foreground when the widget were in active or pressed states.
Returns the value specified for option in style.
If state is specified, it is expected to be a sequence of one or more states. If the default argument is set, it is used as a fallback value in case no specification for option is found.
To check what font a Button uses by default:
Define the widget layout for given style. If layoutspec is omitted, return the layout specification for given style.
layoutspec, if specified, is expected to be a list or some other sequence type (excluding strings), where each item should be a tuple and the first item is the layout name and the second item should have the format described in Layouts.
To understand the format, see the following example (it is not intended to do anything useful):
Create a new element in the current theme, of the given etype which is expected to be either “image”, “from” or “vsapi”. The latter is only available in Tk 8.6a for Windows XP and Vista and is not described here.
If “image” is used, args should contain the default image name followed by statespec/value pairs (this is the imagespec), and kw may have the following options:
padding is a list of up to four integers, specifying the left, top, right, and bottom borders, respectively.
Specifies a minimum height for the element. If less than zero, the base image’s height is used as a default.
Specifies the element’s interior padding. Defaults to border’s value if not specified.
Specifies how the image is placed within the final parcel. spec contains zero or more characters “n”, “s”, “w”, or “e”.
Specifies a minimum width for the element. If less than zero, the base image’s width is used as a default.
If “from” is used as the value of etype, element_create() will clone an existing element. args is expected to contain a themename, from which the element will be cloned, and optionally an element to clone from. If this element to clone from is not specified, an empty element will be used. kw is discarded.
Returns the list of elements defined in the current theme.
Returns the list of elementname’s options.
Create a new theme.
It is an error if themename already exists. If parent is specified, the new theme will inherit styles, elements and layouts from the parent theme. If settings are present they are expected to have the same syntax used for theme_settings().
Temporarily sets the current theme to themename, apply specified settings and then restore the previous theme.
Each key in settings is a style and each value may contain the keys ‘configure’, ‘map’, ‘layout’ and ‘element create’ and they are expected to have the same format as specified by the methods Style.configure(), Style.map(), Style.layout() and Style.element_create() respectively.
As an example, let’s change the Combobox for the default theme a bit:
Returns a list of all known themes.
If themename is not given, returns the theme in use. Otherwise, sets the current theme to themename, refreshes all widgets and emits a <<ThemeChanged>> event.
A layout can be just None, if it takes no options, or a dict of options specifying how to arrange the element. The layout mechanism uses a simplified version of the pack geometry manager: given an initial cavity, each element is allocated a parcel. Valid options/values are:
Specifies which side of the cavity to place the element; one of top, right, bottom or left. If omitted, the element occupies the entire cavity.
Specifies where the element is placed inside its allocated parcel.
If set to 1, causes the element and all of its descendants to be treated as a single element for the purposes of Widget.identify() et al. It’s used for things like scrollbar thumbs with grips.
Specifies a list of elements to place inside the element. Each element is a tuple (or other sequence type) where the first item is the layout name, and the other is a Layout.


If newindex is specified, sets the combobox value to the element position newindex. Otherwise, returns the index of the current value or -1 if the current value is not in the values list.
Returns the current value of the combobox.
Sets the value of the combobox to value.


If newindex is specified, sets the combobox value to the element position newindex. Otherwise, returns the index of the current value or -1 if the current value is not in the values list.


Returns the current value of the combobox.


Sets the value of the combobox to value.


Adds a new tab to the notebook.
If window is currently managed by the notebook but hidden, it is restored to its previous position.
See Tab Options for the list of available options.
Removes the tab specified by tab_id, unmaps and unmanages the associated window.
Hides the tab specified by tab_id.
The tab will not be displayed, but the associated window remains managed by the notebook and its configuration remembered. Hidden tabs may be restored with the add() command.
Returns the name of the tab element at position x, y, or the empty string if none.
Returns the numeric index of the tab specified by tab_id, or the total number of tabs if tab_id is the string “end”.
Inserts a pane at the specified position.
pos is either the string “end”, an integer index, or the name of a managed child. If child is already managed by the notebook, moves it to the specified position.
See Tab Options for the list of available options.
Selects the specified tab_id.
The associated child window will be displayed, and the previously-selected window (if different) is unmapped. If tab_id is omitted, returns the widget name of the currently selected pane.
Query or modify the options of the specific tab_id.
If kw is not given, returns a dictionary of the tab option values. If option is specified, returns the value of that option. Otherwise, sets the options to the corresponding values.
Returns a list of windows managed by the notebook.
Enable keyboard traversal for a toplevel window containing this notebook.
This will extend the bindings for the toplevel window containing the notebook as follows:
Multiple notebooks in a single toplevel may be enabled for traversal, including nested notebooks. However, notebook traversal only works properly if all panes have the notebook they are in as master.


Adds a new tab to the notebook.
If window is currently managed by the notebook but hidden, it is restored to its previous position.
See Tab Options for the list of available options.


Enable keyboard traversal for a toplevel window containing this notebook.
This will extend the bindings for the toplevel window containing the notebook as follows:
Multiple notebooks in a single toplevel may be enabled for traversal, including nested notebooks. However, notebook traversal only works properly if all panes have the notebook they are in as master.


Removes the tab specified by tab_id, unmaps and unmanages the associated window.


Hides the tab specified by tab_id.
The tab will not be displayed, but the associated window remains managed by the notebook and its configuration remembered. Hidden tabs may be restored with the add() command.


Returns the name of the tab element at position x, y, or the empty string if none.


Returns the numeric index of the tab specified by tab_id, or the total number of tabs if tab_id is the string “end”.


Inserts a pane at the specified position.
pos is either the string “end”, an integer index, or the name of a managed child. If child is already managed by the notebook, moves it to the specified position.
See Tab Options for the list of available options.


Selects the specified tab_id.
The associated child window will be displayed, and the previously-selected window (if different) is unmapped. If tab_id is omitted, returns the widget name of the currently selected pane.


Query or modify the options of the specific tab_id.
If kw is not given, returns a dictionary of the tab option values. If option is specified, returns the value of that option. Otherwise, sets the options to the corresponding values.


Returns a list of windows managed by the notebook.


Begin autoincrement mode: schedules a recurring timer event that calls Progressbar.step() every interval milliseconds. If omitted, interval defaults to 50 milliseconds.
Increments the progress bar’s value by amount.
amount defaults to 1.0 if omitted.
Stop autoincrement mode: cancels any recurring timer event initiated by Progressbar.start() for this progress bar.


Begin autoincrement mode: schedules a recurring timer event that calls Progressbar.step() every interval milliseconds. If omitted, interval defaults to 50 milliseconds.


Increments the progress bar’s value by amount.
amount defaults to 1.0 if omitted.


Stop autoincrement mode: cancels any recurring timer event initiated by Progressbar.start() for this progress bar.


Returns the current value of the spinbox.
Sets the value of the spinbox to value.


Returns the current value of the spinbox.


This class is used to manipulate the style database.
Query or set the default value of the specified option(s) in style.
Each key in kw is an option and each value is a string identifying the value for that option.
For example, to change every default button to be a flat button with some padding and a different background color:
Query or sets dynamic values of the specified option(s) in style.
Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, lists, or some other preference. A statespec is a compound of one or more states and then a value.
An example may make it more understandable:
Note that the order of the (states, value) sequences for an option does matter, if the order is changed to [('active', 'blue'), ('pressed',
'red')] in the foreground option, for example, the result would be a blue foreground when the widget were in active or pressed states.
Returns the value specified for option in style.
If state is specified, it is expected to be a sequence of one or more states. If the default argument is set, it is used as a fallback value in case no specification for option is found.
To check what font a Button uses by default:
Define the widget layout for given style. If layoutspec is omitted, return the layout specification for given style.
layoutspec, if specified, is expected to be a list or some other sequence type (excluding strings), where each item should be a tuple and the first item is the layout name and the second item should have the format described in Layouts.
To understand the format, see the following example (it is not intended to do anything useful):
Create a new element in the current theme, of the given etype which is expected to be either “image”, “from” or “vsapi”. The latter is only available in Tk 8.6a for Windows XP and Vista and is not described here.
If “image” is used, args should contain the default image name followed by statespec/value pairs (this is the imagespec), and kw may have the following options:
padding is a list of up to four integers, specifying the left, top, right, and bottom borders, respectively.
Specifies a minimum height for the element. If less than zero, the base image’s height is used as a default.
Specifies the element’s interior padding. Defaults to border’s value if not specified.
Specifies how the image is placed within the final parcel. spec contains zero or more characters “n”, “s”, “w”, or “e”.
Specifies a minimum width for the element. If less than zero, the base image’s width is used as a default.
If “from” is used as the value of etype, element_create() will clone an existing element. args is expected to contain a themename, from which the element will be cloned, and optionally an element to clone from. If this element to clone from is not specified, an empty element will be used. kw is discarded.
Returns the list of elements defined in the current theme.
Returns the list of elementname’s options.
Create a new theme.
It is an error if themename already exists. If parent is specified, the new theme will inherit styles, elements and layouts from the parent theme. If settings are present they are expected to have the same syntax used for theme_settings().
Temporarily sets the current theme to themename, apply specified settings and then restore the previous theme.
Each key in settings is a style and each value may contain the keys ‘configure’, ‘map’, ‘layout’ and ‘element create’ and they are expected to have the same format as specified by the methods Style.configure(), Style.map(), Style.layout() and Style.element_create() respectively.
As an example, let’s change the Combobox for the default theme a bit:
Returns a list of all known themes.
If themename is not given, returns the theme in use. Otherwise, sets the current theme to themename, refreshes all widgets and emits a <<ThemeChanged>> event.


Query or set the default value of the specified option(s) in style.
Each key in kw is an option and each value is a string identifying the value for that option.
For example, to change every default button to be a flat button with some padding and a different background color:


Create a new element in the current theme, of the given etype which is expected to be either “image”, “from” or “vsapi”. The latter is only available in Tk 8.6a for Windows XP and Vista and is not described here.
If “image” is used, args should contain the default image name followed by statespec/value pairs (this is the imagespec), and kw may have the following options:
padding is a list of up to four integers, specifying the left, top, right, and bottom borders, respectively.
Specifies a minimum height for the element. If less than zero, the base image’s height is used as a default.
Specifies the element’s interior padding. Defaults to border’s value if not specified.
Specifies how the image is placed within the final parcel. spec contains zero or more characters “n”, “s”, “w”, or “e”.
Specifies a minimum width for the element. If less than zero, the base image’s width is used as a default.
If “from” is used as the value of etype, element_create() will clone an existing element. args is expected to contain a themename, from which the element will be cloned, and optionally an element to clone from. If this element to clone from is not specified, an empty element will be used. kw is discarded.


Returns the list of elements defined in the current theme.


Returns the list of elementname’s options.


Define the widget layout for given style. If layoutspec is omitted, return the layout specification for given style.
layoutspec, if specified, is expected to be a list or some other sequence type (excluding strings), where each item should be a tuple and the first item is the layout name and the second item should have the format described in Layouts.
To understand the format, see the following example (it is not intended to do anything useful):


Returns the value specified for option in style.
If state is specified, it is expected to be a sequence of one or more states. If the default argument is set, it is used as a fallback value in case no specification for option is found.
To check what font a Button uses by default:


Query or sets dynamic values of the specified option(s) in style.
Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, lists, or some other preference. A statespec is a compound of one or more states and then a value.
An example may make it more understandable:
Note that the order of the (states, value) sequences for an option does matter, if the order is changed to [('active', 'blue'), ('pressed',
'red')] in the foreground option, for example, the result would be a blue foreground when the widget were in active or pressed states.


Create a new theme.
It is an error if themename already exists. If parent is specified, the new theme will inherit styles, elements and layouts from the parent theme. If settings are present they are expected to have the same syntax used for theme_settings().


Temporarily sets the current theme to themename, apply specified settings and then restore the previous theme.
Each key in settings is a style and each value may contain the keys ‘configure’, ‘map’, ‘layout’ and ‘element create’ and they are expected to have the same format as specified by the methods Style.configure(), Style.map(), Style.layout() and Style.element_create() respectively.
As an example, let’s change the Combobox for the default theme a bit:


If themename is not given, returns the theme in use. Otherwise, sets the current theme to themename, refreshes all widgets and emits a <<ThemeChanged>> event.


Returns the bounding box (relative to the treeview widget’s window) of the specified item in the form (x, y, width, height).
If column is specified, returns the bounding box of that cell. If the item is not visible (i.e., if it is a descendant of a closed item or is scrolled offscreen), returns an empty string.
Returns the list of children belonging to item.
If item is not specified, returns root children.
Replaces item’s child with newchildren.
Children present in item that are not present in newchildren are detached from the tree. No items in newchildren may be an ancestor of item. Note that not specifying newchildren results in detaching item’s children.
Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.
The valid options/values are:
Returns the column name. This is a read-only option.
Specifies how the text in this column should be aligned with respect to the cell.
The minimum width of the column in pixels. The treeview widget will not make the column any smaller than specified by this option when the widget is resized or the user drags a column.
Specifies whether the column’s width should be adjusted when the widget is resized.
The width of the column in pixels.
To configure the tree column, call this with column = “#0”
Delete all specified items and all their descendants.
The root item may not be deleted.
Unlinks all of the specified items from the tree.
The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed.
The root item may not be detached.
Returns True if the specified item is present in the tree.
If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or ‘’ if there is none.
Query or modify the heading options for the specified column.
If kw is not given, returns a dict of the heading option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.
The valid options/values are:
The text to display in the column heading.
Specifies an image to display to the right of the column heading.
Specifies how the heading text should be aligned. One of the standard Tk anchor values.
A callback to be invoked when the heading label is pressed.
To configure the tree column heading, call this with column = “#0”.
Returns a description of the specified component under the point given by x and y, or the empty string if no such component is present at that position.
Returns the item ID of the item at position y.
Returns the data column identifier of the cell at position x.
The tree column has ID #0.
Returns one of:
region
meaning
heading
Tree heading area.
separator
Space between two columns headings.
tree
The tree area.
cell
A data cell.
Availability: Tk 8.6.
Returns the element at position x, y.
Availability: Tk 8.6.
Returns the integer index of item within its parent’s list of children.
Creates a new item and returns the item identifier of the newly created item.
parent is the item ID of the parent item, or the empty string to create a new top-level item. index is an integer, or the value “end”, specifying where in the list of parent’s children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning; if index is greater than or equal to the current number of children, it is inserted at the end. If iid is specified, it is used as the item identifier; iid must not already exist in the tree. Otherwise, a new unique identifier is generated.
See Item Options for the list of available points.
Query or modify the options for the specified item.
If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by kw.
Moves item to position index in parent’s list of children.
It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning; if greater than or equal to the number of children, it is moved to the end. If item was detached it is reattached.
Returns the identifier of item’s next sibling, or ‘’ if item is the last child of its parent.
Returns the ID of the parent of item, or ‘’ if item is at the top level of the hierarchy.
Returns the identifier of item’s previous sibling, or ‘’ if item is the first child of its parent.
An alias for Treeview.move().
Ensure that item is visible.
Sets all of item’s ancestors open option to True, and scrolls the widget if necessary so that item is within the visible portion of the tree.
Returns a tuple of selected items.
Changed in version 3.8: selection() no longer takes arguments. For changing the selection state use the following selection methods.
items becomes the new selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
Add items to the selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
Remove items from the selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
Toggle the selection state of each item in items.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
With one argument, returns a dictionary of column/value pairs for the specified item. With two arguments, returns the current value of the specified column. With three arguments, sets the value of given column in given item to the specified value.
Bind a callback for the given event sequence to the tag tagname. When an event is delivered to an item, the callbacks for each of the item’s tags option are called.
Query or modify the options for the specified tagname.
If kw is not given, returns a dict of the option settings for tagname. If option is specified, returns the value for that option for the specified tagname. Otherwise, sets the options to the corresponding values for the given tagname.
If item is specified, returns 1 or 0 depending on whether the specified item has the given tagname. Otherwise, returns a list of all items that have the specified tag.
Availability: Tk 8.6
Query or modify horizontal position of the treeview.
Query or modify vertical position of the treeview.


Returns the bounding box (relative to the treeview widget’s window) of the specified item in the form (x, y, width, height).
If column is specified, returns the bounding box of that cell. If the item is not visible (i.e., if it is a descendant of a closed item or is scrolled offscreen), returns an empty string.


Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.
The valid options/values are:
Returns the column name. This is a read-only option.
Specifies how the text in this column should be aligned with respect to the cell.
The minimum width of the column in pixels. The treeview widget will not make the column any smaller than specified by this option when the widget is resized or the user drags a column.
Specifies whether the column’s width should be adjusted when the widget is resized.
The width of the column in pixels.
To configure the tree column, call this with column = “#0”


Delete all specified items and all their descendants.
The root item may not be deleted.


Unlinks all of the specified items from the tree.
The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed.
The root item may not be detached.


Returns True if the specified item is present in the tree.


If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or ‘’ if there is none.


Returns the list of children belonging to item.
If item is not specified, returns root children.


Query or modify the heading options for the specified column.
If kw is not given, returns a dict of the heading option values. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values.
The valid options/values are:
The text to display in the column heading.
Specifies an image to display to the right of the column heading.
Specifies how the heading text should be aligned. One of the standard Tk anchor values.
A callback to be invoked when the heading label is pressed.
To configure the tree column heading, call this with column = “#0”.


Returns a description of the specified component under the point given by x and y, or the empty string if no such component is present at that position.


Returns the data column identifier of the cell at position x.
The tree column has ID #0.


Returns the element at position x, y.
Availability: Tk 8.6.


Returns one of:
region
meaning
heading
Tree heading area.
separator
Space between two columns headings.
tree
The tree area.
cell
A data cell.
Availability: Tk 8.6.


Returns the item ID of the item at position y.


Returns the integer index of item within its parent’s list of children.


Creates a new item and returns the item identifier of the newly created item.
parent is the item ID of the parent item, or the empty string to create a new top-level item. index is an integer, or the value “end”, specifying where in the list of parent’s children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning; if index is greater than or equal to the current number of children, it is inserted at the end. If iid is specified, it is used as the item identifier; iid must not already exist in the tree. Otherwise, a new unique identifier is generated.
See Item Options for the list of available points.


Query or modify the options for the specified item.
If no options are given, a dict with options/values for the item is returned. If option is specified then the value for that option is returned. Otherwise, sets the options to the corresponding values as given by kw.


Moves item to position index in parent’s list of children.
It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning; if greater than or equal to the number of children, it is moved to the end. If item was detached it is reattached.


Returns the identifier of item’s next sibling, or ‘’ if item is the last child of its parent.


Returns the ID of the parent of item, or ‘’ if item is at the top level of the hierarchy.


Returns the identifier of item’s previous sibling, or ‘’ if item is the first child of its parent.


Ensure that item is visible.
Sets all of item’s ancestors open option to True, and scrolls the widget if necessary so that item is within the visible portion of the tree.


Returns a tuple of selected items.
Changed in version 3.8: selection() no longer takes arguments. For changing the selection state use the following selection methods.


Add items to the selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.


Remove items from the selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.


items becomes the new selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.


Toggle the selection state of each item in items.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.


With one argument, returns a dictionary of column/value pairs for the specified item. With two arguments, returns the current value of the specified column. With three arguments, sets the value of given column in given item to the specified value.


Replaces item’s child with newchildren.
Children present in item that are not present in newchildren are detached from the tree. No items in newchildren may be an ancestor of item. Note that not specifying newchildren results in detaching item’s children.


Bind a callback for the given event sequence to the tag tagname. When an event is delivered to an item, the callbacks for each of the item’s tags option are called.


Query or modify the options for the specified tagname.
If kw is not given, returns a dict of the option settings for tagname. If option is specified, returns the value for that option for the specified tagname. Otherwise, sets the options to the corresponding values for the given tagname.


If item is specified, returns 1 or 0 depending on whether the specified item has the given tagname. Otherwise, returns a list of all items that have the specified tag.
Availability: Tk 8.6


Query or modify horizontal position of the treeview.


Query or modify vertical position of the treeview.


Returns the name of the element at position x y, or the empty string if the point does not lie within any element.
x and y are pixel coordinates relative to the widget.
Test the widget’s state. If a callback is not specified, returns True if the widget state matches statespec and False otherwise. If callback is specified then it is called with args if widget state matches statespec.
Modify or inquire widget state. If statespec is specified, sets the widget state according to it and return a new statespec indicating which flags were changed. If statespec is not specified, returns the currently-enabled state flags.
statespec will usually be a list or a tuple.


Returns the name of the element at position x y, or the empty string if the point does not lie within any element.
x and y are pixel coordinates relative to the widget.


Test the widget’s state. If a callback is not specified, returns True if the widget state matches statespec and False otherwise. If callback is specified then it is called with args if widget state matches statespec.


Modify or inquire widget state. If statespec is specified, sets the widget state according to it and return a new statespec indicating which flags were changed. If statespec is not specified, returns the currently-enabled state flags.


Registers the file handler callback function func. The file argument may either be an object with a fileno() method (such as a file or socket object), or an integer file descriptor. The mask argument is an ORed combination of any of the three constants below. The callback is called as follows:


Source code: Lib/token.py
This module provides constants which represent the numeric values of leaf nodes of the parse tree (terminal tokens). Refer to the file Grammar/Grammar in the Python distribution for the definitions of the names in the context of the language grammar. The specific numeric values which the names map to may change between Python versions.
The module also provides a mapping from numeric codes to names and some functions. The functions mirror definitions in the Python C header files.
Dictionary mapping the numeric values of the constants defined in this module back to name strings, allowing more human-readable representation of parse trees to be generated.
Return True for terminal token values.
Return True for non-terminal token values.
Return True if x is the marker indicating the end of input.
The token constants are:
Token value for "(".
Token value for ")".
Token value for "[".
Token value for "]".
Token value for ":".
Token value for ",".
Token value for ";".
Token value for "+".
Token value for "-".
Token value for "*".
Token value for "/".
Token value for "|".
Token value for "&".
Token value for "<".
Token value for ">".
Token value for "=".
Token value for ".".
Token value for "%".
Token value for "{".
Token value for "}".
Token value for "==".
Token value for "!=".
Token value for "<=".
Token value for ">=".
Token value for "~".
Token value for "^".
Token value for "<<".
Token value for ">>".
Token value for "**".
Token value for "+=".
Token value for "-=".
Token value for "*=".
Token value for "/=".
Token value for "%=".
Token value for "&=".
Token value for "|=".
Token value for "^=".
Token value for "<<=".
Token value for ">>=".
Token value for "**=".
Token value for "//".
Token value for "//=".
Token value for "@".
Token value for "@=".
Token value for "->".
Token value for "...".
Token value for ":=".
The following token type values aren’t used by the C tokenizer but are needed for the tokenize module.
Token value used to indicate a comment.
Token value used to indicate a non-terminating newline. The NEWLINE token indicates the end of a logical line of Python code; NL tokens are generated when a logical line of code is continued over multiple physical lines.
Token value that indicates the encoding used to decode the source bytes into text. The first token returned by tokenize.tokenize() will always be an ENCODING token.
Token value indicating that a type comment was recognized. Such tokens are only produced when ast.parse() is invoked with type_comments=True.
Changed in version 3.5: Added AWAIT and ASYNC tokens.
Changed in version 3.7: Added COMMENT, NL and ENCODING tokens.
Changed in version 3.7: Removed AWAIT and ASYNC tokens. “async” and “await” are now tokenized as NAME tokens.
Changed in version 3.8: Added TYPE_COMMENT, TYPE_IGNORE, COLONEQUAL. Added AWAIT and ASYNC tokens back (they’re needed to support parsing older Python versions for ast.parse() with feature_version set to 6 or lower).


Token value that indicates the encoding used to decode the source bytes into text. The first token returned by tokenize.tokenize() will always be an ENCODING token.


Return True if x is the marker indicating the end of input.


Return True for non-terminal token values.


Token value used to indicate a non-terminating newline. The NEWLINE token indicates the end of a logical line of Python code; NL tokens are generated when a logical line of code is continued over multiple physical lines.


Dictionary mapping the numeric values of the constants defined in this module back to name strings, allowing more human-readable representation of parse trees to be generated.


Source code: Lib/tokenize.py
The tokenize module provides a lexical scanner for Python source code, implemented in Python. The scanner in this module returns comments as tokens as well, making it useful for implementing “pretty-printers”, including colorizers for on-screen displays.
To simplify token stream handling, all operator and delimiter tokens and Ellipsis are returned using the generic OP token type. The exact type can be determined by checking the exact_type property on the named tuple returned from tokenize.tokenize().
The primary entry point is a generator:
The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the io.IOBase.readline() method of file objects. Each call to the function should return one line of input as bytes.
The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the physical line. The 5 tuple is returned as a named tuple with the field names: type string start end line.
The returned named tuple has an additional property named exact_type that contains the exact operator type for OP tokens. For all other token types exact_type equals the named tuple type field.
Changed in version 3.1: Added support for named tuples.
Changed in version 3.3: Added support for exact_type.
tokenize() determines the source encoding of the file by looking for a UTF-8 BOM or encoding cookie, according to PEP 263.
Tokenize a source reading unicode strings instead of bytes.
Like tokenize(), the readline argument is a callable returning a single line of input. However, generate_tokens() expects readline to return a str object rather than bytes.
The result is an iterator yielding named tuples, exactly like tokenize(). It does not yield an ENCODING token.
All constants from the token module are also exported from tokenize.
Another function is provided to reverse the tokenization process. This is useful for creating tools that tokenize a script, modify the token stream, and write back the modified script.
Converts tokens back into Python source code. The iterable must return sequences with at least two elements, the token type and the token string. Any additional sequence elements are ignored.
The reconstructed script is returned as a single string. The result is guaranteed to tokenize back to match the input so that the conversion is lossless and round-trips are assured. The guarantee applies only to the token type and token string as the spacing between tokens (column positions) may change.
It returns bytes, encoded using the ENCODING token, which is the first token sequence output by tokenize(). If there is no encoding token in the input, it returns a str instead.
tokenize() needs to detect the encoding of source files it tokenizes. The function it uses to do this is available:
The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator.
It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (not decoded from bytes) it has read in.
It detects the encoding from the presence of a UTF-8 BOM or an encoding cookie as specified in PEP 263. If both a BOM and a cookie are present, but disagree, a SyntaxError will be raised. Note that if the BOM is found, 'utf-8-sig' will be returned as an encoding.
If no encoding is specified, then the default of 'utf-8' will be returned.
Use open() to open Python source files: it uses detect_encoding() to detect the file encoding.
Open a file in read only mode using the encoding detected by detect_encoding().
New in version 3.2.
Raised when either a docstring or expression that may be split over several lines is not completed anywhere in the file, for example:
or:
Note that unclosed single-quoted strings do not cause an error to be raised. They are tokenized as ERRORTOKEN, followed by the tokenization of their contents.
New in version 3.3.
The tokenize module can be executed as a script from the command line. It is as simple as:
The following options are accepted:
show this help message and exit
display token names using the exact type
If filename.py is specified its contents are tokenized to stdout. Otherwise, tokenization is performed on stdin.
Example of a script rewriter that transforms float literals into Decimal objects:
Example of tokenizing from the command line. The script:
will be tokenized to the following output where the first column is the range of the line/column coordinates where the token is found, the second column is the name of the token, and the final column is the value of the token (if any)
The exact token type names can be displayed using the -e option:
Example of tokenizing a file programmatically, reading unicode strings instead of bytes with generate_tokens():
Or reading bytes directly with tokenize():


The detect_encoding() function is used to detect the encoding that should be used to decode a Python source file. It requires one argument, readline, in the same way as the tokenize() generator.
It will call readline a maximum of twice, and return the encoding used (as a string) and a list of any lines (not decoded from bytes) it has read in.
It detects the encoding from the presence of a UTF-8 BOM or an encoding cookie as specified in PEP 263. If both a BOM and a cookie are present, but disagree, a SyntaxError will be raised. Note that if the BOM is found, 'utf-8-sig' will be returned as an encoding.
If no encoding is specified, then the default of 'utf-8' will be returned.
Use open() to open Python source files: it uses detect_encoding() to detect the file encoding.


Tokenize a source reading unicode strings instead of bytes.
Like tokenize(), the readline argument is a callable returning a single line of input. However, generate_tokens() expects readline to return a str object rather than bytes.
The result is an iterator yielding named tuples, exactly like tokenize(). It does not yield an ENCODING token.


Open a file in read only mode using the encoding detected by detect_encoding().
New in version 3.2.


Raised when either a docstring or expression that may be split over several lines is not completed anywhere in the file, for example:
or:


The tokenize() generator requires one argument, readline, which must be a callable object which provides the same interface as the io.IOBase.readline() method of file objects. Each call to the function should return one line of input as bytes.
The generator produces 5-tuples with these members: the token type; the token string; a 2-tuple (srow, scol) of ints specifying the row and column where the token begins in the source; a 2-tuple (erow, ecol) of ints specifying the row and column where the token ends in the source; and the line on which the token was found. The line passed (the last tuple item) is the physical line. The 5 tuple is returned as a named tuple with the field names: type string start end line.
The returned named tuple has an additional property named exact_type that contains the exact operator type for OP tokens. For all other token types exact_type equals the named tuple type field.
Changed in version 3.1: Added support for named tuples.
Changed in version 3.3: Added support for exact_type.
tokenize() determines the source encoding of the file by looking for a UTF-8 BOM or encoding cookie, according to PEP 263.


Converts tokens back into Python source code. The iterable must return sequences with at least two elements, the token type and the token string. Any additional sequence elements are ignored.
The reconstructed script is returned as a single string. The result is guaranteed to tokenize back to match the input so that the conversion is lossless and round-trips are assured. The guarantee applies only to the token type and token string as the spacing between tokens (column positions) may change.
It returns bytes, encoded using the ENCODING token, which is the first token sequence output by tokenize(). If there is no encoding token in the input, it returns a str instead.


Source code: Lib/trace.py
The trace module allows you to trace program execution, generate annotated statement coverage listings, print caller/callee relationships and list functions executed during a program run. It can be used in another program or from the command line.
See also
A popular third-party coverage tool that provides HTML output along with advanced features such as branch coverage.
The trace module can be invoked from the command line. It can be as simple as
The above will execute somefile.py and generate annotated listings of all Python modules imported during the execution into the current directory.
Display usage and exit.
Display the version of the module and exit.
New in version 3.8: Added --module option that allows to run an executable module.
At least one of the following options must be specified when invoking trace. The --listfuncs option is mutually exclusive with the --trace and --count options. When --listfuncs is provided, neither --count nor --trace are accepted, and vice versa.
Produce a set of annotated listing files upon program completion that shows how many times each statement was executed. See also --coverdir, --file and --no-report below.
Display lines as they are executed.
Display the functions executed by running the program.
Produce an annotated list from an earlier program run that used the --count and --file option. This does not execute any code.
Display the calling relationships exposed by running the program.
Name of a file to accumulate counts over several tracing runs. Should be used with the --count option.
Directory where the report files go. The coverage report for package.module is written to file dir/package/module.cover.
When generating annotated listings, mark lines which were not executed with >>>>>>.
When using --count or --report, write a brief summary to stdout for each file processed.
Do not generate annotated listings. This is useful if you intend to make several runs with --count, and then produce a single set of annotated listings at the end.
Prefix each line with the time since the program started. Only used while tracing.
These options may be repeated multiple times.
Ignore each of the given module names and its submodules (if it is a package). The argument can be a list of names separated by a comma.
Ignore all modules and packages in the named directory and subdirectories. The argument can be a list of directories separated by os.pathsep.
Create an object to trace execution of a single statement or expression. All parameters are optional. count enables counting of line numbers. trace enables line execution tracing. countfuncs enables listing of the functions called during the run. countcallers enables call relationship tracking. ignoremods is a list of modules or packages to ignore. ignoredirs is a list of directories whose modules or packages should be ignored. infile is the name of the file from which to read stored count information. outfile is the name of the file in which to write updated count information. timing enables a timestamp relative to when tracing was started to be displayed.
Execute the command and gather statistics from the execution with the current tracing parameters. cmd must be a string or code object, suitable for passing into exec().
Execute the command and gather statistics from the execution with the current tracing parameters, in the defined global and local environments. If not defined, globals and locals default to empty dictionaries.
Call func with the given arguments under control of the Trace object with the current tracing parameters.
Return a CoverageResults object that contains the cumulative results of all previous calls to run, runctx and runfunc for the given Trace instance. Does not reset the accumulated trace results.
A container for coverage results, created by Trace.results(). Should not be created directly by the user.
Merge in data from another CoverageResults object.
Write coverage results. Set show_missing to show lines that had no hits. Set summary to include in the output the coverage summary per module. coverdir specifies the directory into which the coverage result files will be output. If None, the results for each source file are placed in its directory.
A simple example demonstrating the use of the programmatic interface:


A container for coverage results, created by Trace.results(). Should not be created directly by the user.
Merge in data from another CoverageResults object.
Write coverage results. Set show_missing to show lines that had no hits. Set summary to include in the output the coverage summary per module. coverdir specifies the directory into which the coverage result files will be output. If None, the results for each source file are placed in its directory.


Merge in data from another CoverageResults object.


Write coverage results. Set show_missing to show lines that had no hits. Set summary to include in the output the coverage summary per module. coverdir specifies the directory into which the coverage result files will be output. If None, the results for each source file are placed in its directory.


Create an object to trace execution of a single statement or expression. All parameters are optional. count enables counting of line numbers. trace enables line execution tracing. countfuncs enables listing of the functions called during the run. countcallers enables call relationship tracking. ignoremods is a list of modules or packages to ignore. ignoredirs is a list of directories whose modules or packages should be ignored. infile is the name of the file from which to read stored count information. outfile is the name of the file in which to write updated count information. timing enables a timestamp relative to when tracing was started to be displayed.
Execute the command and gather statistics from the execution with the current tracing parameters. cmd must be a string or code object, suitable for passing into exec().
Execute the command and gather statistics from the execution with the current tracing parameters, in the defined global and local environments. If not defined, globals and locals default to empty dictionaries.
Call func with the given arguments under control of the Trace object with the current tracing parameters.
Return a CoverageResults object that contains the cumulative results of all previous calls to run, runctx and runfunc for the given Trace instance. Does not reset the accumulated trace results.


Return a CoverageResults object that contains the cumulative results of all previous calls to run, runctx and runfunc for the given Trace instance. Does not reset the accumulated trace results.


Execute the command and gather statistics from the execution with the current tracing parameters. cmd must be a string or code object, suitable for passing into exec().


Execute the command and gather statistics from the execution with the current tracing parameters, in the defined global and local environments. If not defined, globals and locals default to empty dictionaries.


Call func with the given arguments under control of the Trace object with the current tracing parameters.


Source code: Lib/traceback.py
This module provides a standard interface to extract, format and print stack traces of Python programs. It exactly mimics the behavior of the Python interpreter when it prints a stack trace. This is useful when you want to print stack traces under program control, such as in a “wrapper” around the interpreter.
The module uses traceback objects — this is the object type that is stored in the sys.last_traceback variable and returned as the third item from sys.exc_info().
The module defines the following functions:
Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output.
Changed in version 3.5: Added negative limit support.
Print exception information and stack trace entries from traceback object tb to file. This differs from print_tb() in the following ways:
The optional limit argument has the same meaning as for print_tb(). If chain is true (the default), then chained exceptions (the __cause__ or __context__ attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception.
Changed in version 3.5: The etype argument is ignored and inferred from the type of value.
This is a shorthand for print_exception(*sys.exc_info(), limit, file,
chain).
This is a shorthand for print_exception(sys.last_type, sys.last_value,
sys.last_traceback, limit, file, chain). In general it will work only after an exception has reached an interactive prompt (see sys.last_type).
Print up to limit stack trace entries (starting from the invocation point) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start. The optional file argument has the same meaning as for print_tb().
Changed in version 3.5: Added negative limit support.
Return a StackSummary object representing a list of “pre-processed” stack trace entries extracted from the traceback object tb. It is useful for alternate formatting of stack traces. The optional limit argument has the same meaning as for print_tb(). A “pre-processed” stack trace entry is a FrameSummary object containing attributes filename, lineno, name, and line representing the information that is usually printed for a stack trace. The line is a string with leading and trailing whitespace stripped; if the source is not available it is None.
Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional f and limit arguments have the same meaning as for print_stack().
Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None.
Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list.
Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception().
Changed in version 3.5: The etype argument is ignored and inferred from the type of value.
This is like print_exc(limit) but returns a string instead of printing to a file.
A shorthand for format_list(extract_tb(tb, limit)).
A shorthand for format_list(extract_stack(f, limit)).
Clears the local variables of all the stack frames in a traceback tb by calling the clear() method of each frame object.
New in version 3.4.
Walk a stack following f.f_back from the given frame, yielding the frame and line number for each frame. If f is None, the current stack is used. This helper is used with StackSummary.extract().
New in version 3.5.
Walk a traceback following tb_next yielding the frame and line number for each frame. This helper is used with StackSummary.extract().
New in version 3.5.
The module also defines the following classes:
New in version 3.5.
TracebackException objects are created from actual exceptions to capture data for later printing in a lightweight fashion.
Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.
Note that when locals are captured, they are also shown in the traceback.
A TracebackException of the original __cause__.
A TracebackException of the original __context__.
The __suppress_context__ value from the original exception.
A StackSummary representing the traceback.
The class of the original traceback.
For syntax errors - the file name where the error occurred.
For syntax errors - the line number where the error occurred.
For syntax errors - the text where the error occurred.
For syntax errors - the offset into the text where the error occurred.
For syntax errors - the compiler error message.
Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.
Note that when locals are captured, they are also shown in the traceback.
Format the exception.
If chain is not True, __cause__ and __context__ will not be formatted.
The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file.
The message indicating which exception occurred is always the last string in the output.
Format the exception part of the traceback.
The return value is a generator of strings, each ending in a newline.
Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred.
The message indicating which exception occurred is always the last string in the output.
New in version 3.5.
StackSummary objects represent a call stack ready for formatting.
Construct a StackSummary object from a frame generator (such as is returned by walk_stack() or walk_tb()).
If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is False, the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper (which may be valuable if it may not actually get formatted). If capture_locals is True the local variables in each FrameSummary are captured as object representations.
Construct a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements.
Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines.
For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions.
Changed in version 3.6: Long sequences of repeated frames are now abbreviated.
New in version 3.5.
FrameSummary objects represent a single frame in a traceback.
Represent a single frame in the traceback or stack that is being formatted or printed. It may optionally have a stringified version of the frames locals included in it. If lookup_line is False, the source code is not looked up until the FrameSummary has the line attribute accessed (which also happens when casting it to a tuple). line may be directly provided, and will prevent line lookups happening at all. locals is an optional local variable dictionary, and if supplied the variable representations are stored in the summary for later display.
This simple example implements a basic read-eval-print loop, similar to (but less useful than) the standard Python interactive interpreter loop. For a more complete implementation of the interpreter loop, refer to the code module.
The following example demonstrates the different ways to print and format the exception and traceback:
The output for the example would look similar to this:
The following example shows the different ways to print and format the stack:
This last example demonstrates the final few formatting functions:


Clears the local variables of all the stack frames in a traceback tb by calling the clear() method of each frame object.
New in version 3.4.


Extract the raw traceback from the current stack frame. The return value has the same format as for extract_tb(). The optional f and limit arguments have the same meaning as for print_stack().


Return a StackSummary object representing a list of “pre-processed” stack trace entries extracted from the traceback object tb. It is useful for alternate formatting of stack traces. The optional limit argument has the same meaning as for print_tb(). A “pre-processed” stack trace entry is a FrameSummary object containing attributes filename, lineno, name, and line representing the information that is usually printed for a stack trace. The line is a string with leading and trailing whitespace stripped; if the source is not available it is None.


This is like print_exc(limit) but returns a string instead of printing to a file.


Format a stack trace and the exception information. The arguments have the same meaning as the corresponding arguments to print_exception(). The return value is a list of strings, each ending in a newline and some containing internal newlines. When these lines are concatenated and printed, exactly the same text is printed as does print_exception().
Changed in version 3.5: The etype argument is ignored and inferred from the type of value.


Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is the always last string in the list.


Given a list of tuples or FrameSummary objects as returned by extract_tb() or extract_stack(), return a list of strings ready for printing. Each string in the resulting list corresponds to the item with the same index in the argument list. Each string ends in a newline; the strings may contain internal newlines as well, for those items whose source text line is not None.


A shorthand for format_list(extract_stack(f, limit)).


A shorthand for format_list(extract_tb(tb, limit)).


Represent a single frame in the traceback or stack that is being formatted or printed. It may optionally have a stringified version of the frames locals included in it. If lookup_line is False, the source code is not looked up until the FrameSummary has the line attribute accessed (which also happens when casting it to a tuple). line may be directly provided, and will prevent line lookups happening at all. locals is an optional local variable dictionary, and if supplied the variable representations are stored in the summary for later display.


This is a shorthand for print_exception(*sys.exc_info(), limit, file,
chain).


Print exception information and stack trace entries from traceback object tb to file. This differs from print_tb() in the following ways:
The optional limit argument has the same meaning as for print_tb(). If chain is true (the default), then chained exceptions (the __cause__ or __context__ attributes of the exception) will be printed as well, like the interpreter itself does when printing an unhandled exception.
Changed in version 3.5: The etype argument is ignored and inferred from the type of value.


This is a shorthand for print_exception(sys.last_type, sys.last_value,
sys.last_traceback, limit, file, chain). In general it will work only after an exception has reached an interactive prompt (see sys.last_type).


Print up to limit stack trace entries (starting from the invocation point) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. The optional f argument can be used to specify an alternate stack frame to start. The optional file argument has the same meaning as for print_tb().
Changed in version 3.5: Added negative limit support.


Print up to limit stack trace entries from traceback object tb (starting from the caller’s frame) if limit is positive. Otherwise, print the last abs(limit) entries. If limit is omitted or None, all entries are printed. If file is omitted or None, the output goes to sys.stderr; otherwise it should be an open file or file-like object to receive the output.
Changed in version 3.5: Added negative limit support.


Construct a StackSummary object from a frame generator (such as is returned by walk_stack() or walk_tb()).
If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is False, the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper (which may be valuable if it may not actually get formatted). If capture_locals is True the local variables in each FrameSummary are captured as object representations.
Construct a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements.
Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines.
For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions.
Changed in version 3.6: Long sequences of repeated frames are now abbreviated.


Construct a StackSummary object from a frame generator (such as is returned by walk_stack() or walk_tb()).
If limit is supplied, only this many frames are taken from frame_gen. If lookup_lines is False, the returned FrameSummary objects will not have read their lines in yet, making the cost of creating the StackSummary cheaper (which may be valuable if it may not actually get formatted). If capture_locals is True the local variables in each FrameSummary are captured as object representations.


Returns a list of strings ready for printing. Each string in the resulting list corresponds to a single frame from the stack. Each string ends in a newline; the strings may contain internal newlines as well, for those items with source text lines.
For long sequences of the same frame and line, the first few repetitions are shown, followed by a summary line stating the exact number of further repetitions.
Changed in version 3.6: Long sequences of repeated frames are now abbreviated.


Construct a StackSummary object from a supplied list of FrameSummary objects or old-style list of tuples. Each tuple should be a 4-tuple with filename, lineno, name, line as the elements.


Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.
Note that when locals are captured, they are also shown in the traceback.
A TracebackException of the original __cause__.
A TracebackException of the original __context__.
The __suppress_context__ value from the original exception.
A StackSummary representing the traceback.
The class of the original traceback.
For syntax errors - the file name where the error occurred.
For syntax errors - the line number where the error occurred.
For syntax errors - the text where the error occurred.
For syntax errors - the offset into the text where the error occurred.
For syntax errors - the compiler error message.
Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.
Note that when locals are captured, they are also shown in the traceback.
Format the exception.
If chain is not True, __cause__ and __context__ will not be formatted.
The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file.
The message indicating which exception occurred is always the last string in the output.
Format the exception part of the traceback.
The return value is a generator of strings, each ending in a newline.
Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred.
The message indicating which exception occurred is always the last string in the output.


For syntax errors - the file name where the error occurred.


Format the exception.
If chain is not True, __cause__ and __context__ will not be formatted.
The return value is a generator of strings, each ending in a newline and some containing internal newlines. print_exception() is a wrapper around this method which just prints the lines to a file.
The message indicating which exception occurred is always the last string in the output.


Format the exception part of the traceback.
The return value is a generator of strings, each ending in a newline.
Normally, the generator emits a single string; however, for SyntaxError exceptions, it emits several lines that (when printed) display detailed information about where the syntax error occurred.
The message indicating which exception occurred is always the last string in the output.


Capture an exception for later rendering. limit, lookup_lines and capture_locals are as for the StackSummary class.
Note that when locals are captured, they are also shown in the traceback.


For syntax errors - the line number where the error occurred.


For syntax errors - the compiler error message.


For syntax errors - the offset into the text where the error occurred.


A StackSummary representing the traceback.


For syntax errors - the text where the error occurred.


A TracebackException of the original __cause__.


A TracebackException of the original __context__.


The __suppress_context__ value from the original exception.


Walk a stack following f.f_back from the given frame, yielding the frame and line number for each frame. If f is None, the current stack is used. This helper is used with StackSummary.extract().
New in version 3.5.


Walk a traceback following tb_next yielding the frame and line number for each frame. This helper is used with StackSummary.extract().
New in version 3.5.