We will be using the Tkinter framework. A full tutorial on how to use the different widgets can be found here: An Introduction to Tkinter. Tkinter is the standard Python interface (Tk interface) for the Tk GUI toolkit. The Tk interface module consists of a number of other modules as well. Introduction and Simple Examples. A text widget is used for multi-line text area. The Tkinter text widget is very powerful and flexible and can be used for a wide range of tasks. Though one of the main purposes is to provide simple multi-line areas, as they are often used in forms, text widgets can also be used as simple text editors.
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, thismodule can still be accessed if Tile has been installed. The formermethod using Tk 8.5 provides additional benefits including anti-aliased fontrendering under X11 and window transparency (requiring a compositionwindow 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 itsappearance.
See also
A document introducing theming support for Tk
Using Ttk¶
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
) toautomatically replace the Tk widgets.
This has the direct benefit of using the new widgets which gives a betterlook and feel across platforms; however, the replacement widgets are notcompletely compatible. The main difference is that widget options such as“fg”, “bg” and others related to widget styling are nolonger present in Ttk widgets. Instead, use the ttk.Style
classfor improved styling effects.
See also
A monograph (using Tcl terminology) about differences typicallyencountered when moving applications to use the new widgets.
Ttk 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
andTreeview
. 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
classdocumentation.
Widget¶
ttk.Widget
defines standard options and methods supported by Tkthemed widgets and is not supposed to be directly instantiated.
Standard Options¶
All the ttk
Widgets accepts the following options:
Option | Description |
---|---|
class | Specifies the window class. The class is used when queryingthe option database for the window’s other options, todetermine the default bindtags for the window, and to selectthe widget’s default layout and style. This option isread-only, and may only be specified when the window iscreated. |
cursor | Specifies the mouse cursor to be used for the widget. If setto the empty string (the default), the cursor is inheritedfor the parent widget. |
takefocus | Determines whether the window accepts the focus duringkeyboard traversal. 0, 1 or an empty string is returned.If 0 is returned, it means that the window should be skippedentirely during keyboard traversal. If 1, it means that thewindow should receive the input focus as long as it isviewable. And an empty string means that the traversalscripts make the decision about whether or not to focuson the window. |
style | May be used to specify a custom widget style. |
Scrollable Widget Options¶
The following options are supported by widgets that are controlled by ascrollbar.
Option | Description |
---|---|
xscrollcommand | Used to communicate with horizontal scrollbars. When the view in the widget’s window change, the widgetwill generate a Tcl command based on the scrollcommand. Usually this option consists of the method |
yscrollcommand | Used to communicate with vertical scrollbars.For some more information, see above. |
Label Options¶
The following options are supported by labels, buttons and other button-likewidgets.
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 thetext option resource. |
underline | If set, specifies the index (0-based) of a character tounderline in the text string. The underline character isused for mnemonic activation. |
image | Specifies an image to display. This is a list of 1 or moreelements. The first element is the default image name. Therest of the list if a sequence of statespec/value pairs asdefined by |
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, incharacter widths, to allocate for the text label, if lessthan zero, specifies a minimum width. If zero orunspecified, the natural width of the text label is used. |
Compatibility Options¶
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 thewidget state, but the |
Widget States¶
The widget state is a bitmap of independent state flags.
Flag | Description |
---|---|
active | The mouse cursor is over the widget and pressing a mousebutton 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 andradiobuttons |
background | Windows and Mac have a notion of an “active” or foregroundwindow. The background state is set for widgets in abackground window, and cleared for those in the foregroundwindow |
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 withan exclamation point indicating that the bit is off.
ttk.Widget¶
Besides the methods described below, the ttk.Widget
supports themethods tkinter.Widget.cget()
and tkinter.Widget.configure()
.
tkinter.ttk.
Widget
¶identify
(x, y)¶Returns the name of the element at position xy, or the empty stringif the point does not lie within any element.
x and y are pixel coordinates relative to the widget.
instate
(statespec, callback=None, *args, **kw)¶Test the widget’s state. If a callback is not specified, returns True
if the widget state matches statespec and False
otherwise. If callbackis specified then it is called with args if widget state matchesstatespec.
state
(statespec=None)¶Modify or inquire widget state. If statespec is specified, sets thewidget state according to it and return a new statespec indicatingwhich flags were changed. If statespec is not specified, returnsthe currently-enabled state flags.
statespec will usually be a list or a tuple.
Combobox¶
The ttk.Combobox
widget combines a text field with a pop-down list ofvalues. 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 atttk.Combobox
.
Options¶
This widget accepts the following specific options:
Option | Description |
---|---|
exportselection | Boolean value. If set, the widget selection is linkedto the Window Manager selection (which can be returnedby 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) thatis called immediately before displaying the values. Itmay 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 thedropdown list. In the “normal” state, the text field isdirectly editable. In the “disabled” state, nointeraction is possible. |
textvariable | Specifies a name whose value is linked to the widgetvalue. Whenever the value associated with that namechanges, the widget value is updated, and vice versa.See |
values | Specifies the list of values to display in thedrop-down listbox. |
width | Specifies an integer value indicating the desired widthof the entry window, in average-size characters of thewidget’s font. |
Virtual events¶
The combobox widgets generates a <<ComboboxSelected>> virtual eventwhen the user selects an element from the list of values.
ttk.Combobox¶
tkinter.ttk.
Combobox
¶current
(newindex=None)¶If newindex is specified, sets the combobox value to the elementposition newindex. Otherwise, returns the index of the current value or-1 if the current value is not in the values list.
get
()¶Returns the current value of the combobox.
set
(value)¶Sets the value of the combobox to value.
Spinbox¶
The ttk.Spinbox
widget is a ttk.Entry
enhanced with incrementand 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
.
Options¶
This widget accepts the following specific options:
Option | Description |
---|---|
from | Float value. If set, this is the minimum value towhich the decrement button will decrement. Must bespelled as |
to | Float value. If set, this is the maximum value towhich the increment button will increment. |
increment | Float value. Specifies the amount which theincrement/decrement buttons change thevalue. Defaults to 1.0. |
values | Sequence of string or float values. If specified,the increment/decrement buttons will cycle throughthe items in this sequence rather than incrementingor decrementing numbers. |
wrap | Boolean value. If |
format | String value. This specifies the format of numbersset by the increment/decrement buttons. It must bein the form “%W.Pf”, where W is the padded width ofthe value, P is the precision, and ‘%’ and ‘f’ areliteral. |
command | Python callable. Will be called with no argumentswhenever either of the increment or decrement buttonsare pressed. |
Virtual events¶
The spinbox widget generates an <<Increment>> virtual event when theuser presses <Up>, and a <<Decrement>> virtual event when the userpresses <Down>.
ttk.Spinbox¶
tkinter.ttk.
Spinbox
¶get
()¶Returns the current value of the spinbox.
set
(value)¶Sets the value of the spinbox to value.
Notebook¶
Ttk Notebook widget manages a collection of windows and displays a singleone at a time. Each child window is associated with a tab, which the usermay select to change the currently-displayed window.
Options¶
This widget accepts the following specific options:
Option | Description |
---|---|
height | If present and greater than zero, specifies the desired heightof 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 outsideof the notebook. The padding is a list up to four lengthspecifications left top right bottom. If fewer than fourelements are specified, bottom defaults to top, right defaultsto left, and top defaults to left. |
width | If present and greater than zero, specified the desired widthof the pane area (not including internal padding). Otherwise,the maximum width of all panes is used. |
Tab Options¶
There are also specific options for tabs:
Option | Description |
---|---|
state | Either “normal”, “disabled” or “hidden”. If “disabled”, thenthe tab is not selectable. If “hidden”, then the tab is notshown. |
sticky | Specifies how the child window is positioned within the panearea. Value is a string containing zero or more of thecharacters “n”, “s”, “e” or “w”. Each letter refers to aside (north, south, east or west) that the child window willstick to, as per the |
padding | Specifies the amount of extra space to add between thenotebook and this pane. Syntax is the same as for the optionpadding 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 optionimage described in |
compound | Specifies how to display the image relative to the text, inthe case both options text and image are present. SeeLabel Options for legal values. |
underline | Specifies the index (0-based) of a character to underline inthe text string. The underlined character is used formnemonic activation if |
Tab Identifiers¶
The tab_id present in several methods of ttk.Notebook
may take anyof the following forms:
An integer between zero and the number of tabs
The name of a child window
A positional specification of the form “@x,y”, which identifies the tab
The literal string “current”, which identifies the currently-selected tab
The literal string “end”, which returns the number of tabs (only valid for
Notebook.index()
)
Virtual Events¶
This widget generates a <<NotebookTabChanged>> virtual event after a newtab is selected.
ttk.Notebook¶
tkinter.ttk.
Notebook
¶add
(child, **kw)¶Adds a new tab to the notebook.
If window is currently managed by the notebook but hidden, it isrestored to its previous position.
See Tab Options for the list of available options.
forget
(tab_id)¶Removes the tab specified by tab_id, unmaps and unmanages theassociated window.
hide
(tab_id)¶Hides the tab specified by tab_id.
The tab will not be displayed, but the associated window remainsmanaged by the notebook and its configuration remembered. Hidden tabsmay be restored with the add()
command.
identify
(x, y)¶Returns the name of the tab element at position x, y, or the emptystring if none.
index
(tab_id)¶Returns the numeric index of the tab specified by tab_id, or the totalnumber of tabs if tab_id is the string “end”.
insert
(pos, child, **kw)¶Inserts a pane at the specified position.
pos is either the string “end”, an integer index, or the name of amanaged child. If child is already managed by the notebook, moves it tothe specified position.
See Tab Options for the list of available options.
select
(tab_id=None)¶Selects the specified tab_id.
The associated child window will be displayed, and thepreviously-selected window (if different) is unmapped. If tab_id isomitted, returns the widget name of the currently selected pane.
tab
(tab_id, option=None, **kw)¶Query or modify the options of the specific tab_id.
If kw is not given, returns a dictionary of the tab option values. Ifoption is specified, returns the value of that option. Otherwise,sets the options to the corresponding values.
tabs
()¶Returns a list of windows managed by the notebook.
enable_traversal
()¶Enable keyboard traversal for a toplevel window containing this notebook.
This will extend the bindings for the toplevel window containing thenotebook as follows:
Control-Tab: selects the tab following the currently selected one.
Shift-Control-Tab: selects the tab preceding the currently selected one.
Alt-K: where K is the mnemonic (underlined) character of any tab, willselect that tab.
Multiple notebooks in a single toplevel may be enabled for traversal,including nested notebooks. However, notebook traversal only worksproperly if all panes have the notebook they are in as master.
Progressbar¶
The ttk.Progressbar
widget shows the status of a long-runningoperation. It can operate in two modes: 1) the determinate mode which shows theamount completed relative to the total amount of work to be done and 2) theindeterminate mode which provides an animated display to let the user know thatwork is progressing.
Options¶
This widget accepts the following specific options:
Option | Description |
---|---|
orient | One of “horizontal” or “vertical”. Specifies the orientationof 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 valueincreases by maximum. |
variable | A name which is linked to the option value. If specified, thevalue of the progress bar is automatically set to the value ofthis name whenever the latter is modified. |
phase | Read-only option. The widget periodically increments the valueof this option whenever its value is greater than 0 and, indeterminate mode, less than maximum. This option may be usedby the current theme to provide additional animation effects. |
ttk.Progressbar¶
tkinter.ttk.
Progressbar
¶start
(interval=None)¶Begin autoincrement mode: schedules a recurring timer event that callsProgressbar.step()
every interval milliseconds. If omitted,interval defaults to 50 milliseconds.
step
(amount=None)¶Increments the progress bar’s value by amount.
amount defaults to 1.0 if omitted.
stop
()¶Stop autoincrement mode: cancels any recurring timer event initiated byProgressbar.start()
for this progress bar.
Separator¶
The ttk.Separator
widget displays a horizontal or vertical separatorbar.
It has no other methods besides the ones inherited from ttk.Widget
.
Options¶
This widget accepts the following specific option:
Option | Description |
---|---|
orient | One of “horizontal” or “vertical”. Specifies the orientation ofthe separator. |
Sizegrip¶
The ttk.Sizegrip
widget (also known as a grow box) allows the user toresize the containing toplevel window by pressing and dragging the grip.
This widget has neither specific options nor specific methods, besides theones inherited from ttk.Widget
.
Platform-specific notes¶
On MacOS X, toplevel windows automatically include a built-in size gripby default. Adding a
Sizegrip
is harmless, since the built-ingrip will just mask the widget.
Bugs¶
If the containing toplevel’s position was specified relative to the rightor bottom of the screen (e.g. ….), the
Sizegrip
widget willnot resize the window.This widget supports only “southeast” resizing.
Treeview¶
The ttk.Treeview
widget displays a hierarchical collection of items.Each item has a textual label, an optional image, and an optional list of datavalues. The data values are displayed in successive columns after the treelabel.
The order in which data values are displayed may be controlled by settingthe widget option displaycolumns
. The tree widget can also display columnheadings. Columns may be accessed by number or symbolic names listed in thewidget option columns. See Column Identifiers.
Each item is identified by a unique name. The widget will generate item IDsif 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 thetop level of the hierarchy.
Each item also has a list of tags, which can be used to associate event bindingswith individual items and control the appearance of the item.
The Treeview widget supports horizontal and vertical scrolling, according tothe options described in Scrollable Widget Options and the methodsTreeview.xview()
and Treeview.yview()
.
Options¶
This widget accepts the following specific options:
Option | Description |
---|---|
columns | A list of column identifiers, specifying the number ofcolumns and their names. |
displaycolumns | A list of column identifiers (either symbolic orinteger indices) specifying which data columns aredisplayed and the order in which they appear, or thestring “#all”. |
height | Specifies the number of rows which should be visible.Note: the requested width is determined from the sumof the column widths. |
padding | Specifies the internal padding for the widget. Thepadding is a list of up to four length specifications. |
selectmode | Controls how the built-in class bindings manage theselection. One of “extended”, “browse” or “none”.If set to “extended” (the default), multiple items maybe selected. If “browse”, only a single item will beselected at a time. If “none”, the selection will notbe changed. Note that the application code and tag bindings can setthe selection however they wish, regardless of thevalue 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 allelements. Note: Column #0 always refers to the tree column,even if show=”tree” is not specified. |
Item Options¶
The following item options may be specified for items in the insert and itemwidget 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 widgetoption columns. If there are fewer values than columns, theremaining values are assumed empty. If there are more valuesthan columns, the extra values are ignored. |
open | True/False value indicating whether the item’s children shouldbe displayed or hidden. |
tags | A list of tags associated with this item. |
Tag Options¶
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 optionis empty. |
Column Identifiers¶
Column identifiers take any of the following forms:
A symbolic name from the list of columns option.
An integer n, specifying the nth data column.
A string of the form #n, where n is an integer, specifying the nth displaycolumn.
Notes:
Item’s option values may be displayed in a different order than the orderin which they are stored.
Column #0 always refers to the tree column, even if show=”tree” is notspecified.
A data column number is an index into an item’s option values list; a displaycolumn 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 alwaysrefers to the tree column.
Virtual Events¶
The Treeview widget generates the following virtual events.
Event | Description |
---|---|
<<TreeviewSelect>> | Generated whenever the selection changes. |
<<TreeviewOpen>> | Generated just before settings the focus item toopen=True. |
<<TreeviewClose>> | Generated just after setting the focus item toopen=False. |
The Treeview.focus()
and Treeview.selection()
methods can be usedto determine the affected item or items.
ttk.Treeview¶
tkinter.ttk.
Treeview
¶bbox
(item, column=None)¶Returns the bounding box (relative to the treeview widget’s window) ofthe specified item in the form (x, y, width, height).
If column is specified, returns the bounding box of that cell. If theitem is not visible (i.e., if it is a descendant of a closed item or isscrolled offscreen), returns an empty string.
get_children
(item=None)¶Returns the list of children belonging to item.
If item is not specified, returns root children.
set_children
(item, *newchildren)¶Replaces item’s child with newchildren.
Children present in item that are not present in newchildren aredetached from the tree. No items in newchildren may be an ancestor ofitem. Note that not specifying newchildren results in detachingitem’s children.
column
(column, option=None, **kw)¶Query or modify the options for the specified column.
If kw is not given, returns a dict of the column option values. Ifoption is specified then the value for that option is returned.Otherwise, sets the options to the corresponding values.
The valid options/values are:
- id
Returns the column name. This is a read-only option.
- anchor: One of the standard Tk anchor values.
Specifies how the text in this column should be aligned with respectto the cell.
- minwidth: width
The minimum width of the column in pixels. The treeview widget willnot make the column any smaller than specified by this option whenthe widget is resized or the user drags a column.
- stretch: True/False
Specifies whether the column’s width should be adjusted whenthe widget is resized.
- width: width
The width of the column in pixels.
To configure the tree column, call this with column = “#0”
delete
(*items)¶Delete all specified items and all their descendants.
The root item may not be deleted.
detach
(*items)¶Unlinks all of the specified items from the tree.
The items and all of their descendants are still present, and may bereinserted at another point in the tree, but will not be displayed.
The root item may not be detached.
exists
(item)¶Returns True
if the specified item is present in the tree.
focus
(item=None)¶If item is specified, sets the focus item to item. Otherwise, returnsthe current focus item, or ‘’ if there is none.
heading
(column, option=None, **kw)¶Query or modify the heading options for the specified column.
If kw is not given, returns a dict of the heading option values. Ifoption is specified then the value for that option is returned.Otherwise, sets the options to the corresponding values.
The valid options/values are:
- text: text
The text to display in the column heading.
- image: imageName
Specifies an image to display to the right of the column heading.
- anchor: anchor
Specifies how the heading text should be aligned. One of the standardTk anchor values.
- command: callback
A callback to be invoked when the heading label is pressed.
To configure the tree column heading, call this with column = “#0”.
identify
(component, x, y)¶Returns a description of the specified component under the point givenby x and y, or the empty string if no such component is present atthat position.
identify_row
(y)¶Returns the item ID of the item at position y.
identify_column
(x)¶Returns the data column identifier of the cell at position x.
The tree column has ID #0.
identify_region
(x, y)¶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.
identify_element
(x, y)¶Returns the element at position x, y.
Availability: Tk 8.6.
index
(item)¶Returns the integer index of item within its parent’s list of children.
insert
(parent, index, iid=None, **kw)¶Creates a new item and returns the item identifier of the newly createditem.
parent is the item ID of the parent item, or the empty string to createa 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 atthe beginning; if index is greater than or equal to the current numberof children, it is inserted at the end. If iid is specified, it is usedas 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.
item
(item, option=None, **kw)¶Query or modify the options for the specified item.
If no options are given, a dict with options/values for the item isreturned.If option is specified then the value for that option is returned.Otherwise, sets the options to the corresponding values as given by kw.
move
(item, parent, index)¶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 isless than or equal to zero, item is moved to the beginning; if greaterthan or equal to the number of children, it is moved to the end. If itemwas detached it is reattached.
next
(item)¶Returns the identifier of item’s next sibling, or ‘’ if item is thelast child of its parent.
parent
(item)¶Returns the ID of the parent of item, or ‘’ if item is at the toplevel of the hierarchy.
prev
(item)¶Returns the identifier of item’s previous sibling, or ‘’ if item isthe first child of its parent.
reattach
(item, parent, index)¶An alias for Treeview.move()
.
see
(item)¶Ensure that item is visible.
Sets all of item’s ancestors open option to True
, and scrolls thewidget if necessary so that item is within the visible portion ofthe tree.
selection
(selop=None, items=None)¶If selop is not specified, returns selected items. Otherwise, it willact according to the following selection methods.
Deprecated since version 3.6, will be removed in version 3.8: Using selection()
for changing the selection state is deprecated.Use the following selection methods instead.
selection_set
(*items)¶items becomes the new selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
selection_add
(*items)¶Add items to the selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
selection_remove
(*items)¶Remove items from the selection.
Changed in version 3.6: items can be passed as separate arguments, not just as a single tuple.
selection_toggle
(*items)¶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.
set
(item, column=None, value=None)¶With one argument, returns a dictionary of column/value pairs for thespecified item. With two arguments, returns the current value of thespecified column. With three arguments, sets the value of givencolumn in given item to the specified value.
tag_bind
(tagname, sequence=None, callback=None)¶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 theitem’s tags option are called.
tag_configure
(tagname, option=None, **kw)¶Query or modify the options for the specified tagname.
If kw is not given, returns a dict of the option settings fortagname. If option is specified, returns the value for that optionfor the specified tagname. Otherwise, sets the options to thecorresponding values for the given tagname.
tag_has
(tagname, item=None)¶If item is specified, returns 1 or 0 depending on whether the specifieditem has the given tagname. Otherwise, returns a list of all itemsthat have the specified tag.
Availability: Tk 8.6
xview
(*args)¶Query or modify horizontal position of the treeview.
yview
(*args)¶Query or modify vertical position of the treeview.
Ttk Styling¶
Each widget in ttk
is assigned a style, which specifies the set ofelements making up the widget and how they are arranged, along with dynamicand default settings for element options. By default the style name is thesame as the widget’s class name, but it may be overridden by the widget’s styleoption. If you don’t know the class name of a widget, use the methodMisc.winfo_class()
(somewidget.winfo_class()).
See also
This document explains how the theme engine works
tkinter.ttk.
Style
¶This class is used to manipulate the style database.
configure
(style, query_opt=None, **kw)¶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 identifyingthe value for that option.
For example, to change every default button to be a flat button withsome padding and a different background color:
map
(style, query_opt=None, **kw)¶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 atuple (usually) containing statespecs grouped in tuples, lists, orsome other preference. A statespec is a compound of oneor 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 doesmatter, if the order is changed to [('active','blue'),('pressed','red')]
in the foreground option, for example, the result would be ablue foreground when the widget were in active or pressed states.
lookup
(style, option, state=None, default=None)¶Returns the value specified for option in style.
If state is specified, it is expected to be a sequence of one or morestates. If the default argument is set, it is used as a fallback valuein case no specification for option is found.
To check what font a Button uses by default:
layout
(style, layoutspec=None)¶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 othersequence type (excluding strings), where each item should be a tuple andthe first item is the layout name and the second item should have theformat described in Layouts.
To understand the format, see the following example (it is notintended to do anything useful):
element_create
(elementname, etype, *args, **kw)¶Create a new element in the current theme, of the given etype which isexpected to be either “image”, “from” or “vsapi”. The latter is onlyavailable 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 followedby statespec/value pairs (this is the imagespec), and kw may have thefollowing options:
- border=padding
padding is a list of up to four integers, specifying the left, top,right, and bottom borders, respectively.
- height=height
Specifies a minimum height for the element. If less than zero, thebase image’s height is used as a default.
- padding=padding
Specifies the element’s interior padding. Defaults to border’s valueif not specified.
- sticky=spec
Specifies how the image is placed within the final parcel. speccontains zero or more characters “n”, “s”, “w”, or “e”.
- width=width
Specifies a minimum width for the element. If less than zero, thebase image’s width is used as a default.
If “from” is used as the value of etype,element_create()
will clone an existingelement. args is expected to contain a themename, from whichthe element will be cloned, and optionally an element to clone from.If this element to clone from is not specified, an empty element willbe used. kw is discarded.
element_names
()¶Returns the list of elements defined in the current theme.
element_options
(elementname)¶Returns the list of elementname’s options.
theme_create
(themename, parent=None, settings=None)¶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 parenttheme. If settings are present they are expected to have the samesyntax used for theme_settings()
.
theme_settings
(themename, settings)¶Temporarily sets the current theme to themename, apply specifiedsettings 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 expectedto have the same format as specified by the methodsStyle.configure()
, Style.map()
, Style.layout()
andStyle.element_create()
respectively.
As an example, let’s change the Combobox for the default theme a bit:
theme_names
()¶Returns a list of all known themes.
theme_use
(themename=None)¶If themename is not given, returns the theme in use. Otherwise, setsthe current theme to themename, refreshes all widgets and emits a<<ThemeChanged>> event.
Layouts¶
A layout can be just None
, if it takes no options, or a dict ofoptions specifying how to arrange the element. The layout mechanismuses a simplified version of the pack geometry manager: given aninitial cavity, each element is allocated a parcel. Validoptions/values are:
- side: whichside
Specifies which side of the cavity to place the element; one oftop, right, bottom or left. If omitted, the element occupies theentire cavity.
- sticky: nswe
Specifies where the element is placed inside its allocated parcel.
- unit: 0 or 1
If set to 1, causes the element and all of its descendants to be treated asa single element for the purposes of
Widget.identify()
et al. It’sused for things like scrollbar thumbs with grips.
- children: [sublayout… ]
Specifies a list of elements to place inside the element. Eachelement is a tuple (or other sequence type) where the first item isthe layout name, and the other is a Layout.
Source code:Lib/tkinter/__init__.py
The tkinter
package (“Tk interface”) is the standard Python interface tothe Tk GUI toolkit. Both Tk and tkinter
are available on most Unixplatforms, as well as on Windows systems. (Tk itself is not part of Python; itis maintained at ActiveState.)
Running python-mtkinter
from the command line should open a windowdemonstrating a simple Tk interface, letting you know that tkinter
isproperly installed on your system, and also showing what version of Tcl/Tk isinstalled, so you can read the Tcl/Tk documentation specific to that version.
See also
Tkinter documentation:
The Python Tkinter Topic Guide provides a great deal of information on using Tkfrom Python and links to other sources of information on Tk.
Extensive tutorial plus friendlier widget pages for some of the widgets.
On-line reference material.
Online reference for tkinter supported by effbot.org.
Book by Mark Lutz, has excellent coverage of Tkinter.
Book by Mark Rozerman about building attractive and modern graphical user interfaces with Python and Tkinter.
Book by John Grayson (ISBN 1-884777-81-3).
Tcl/Tk documentation:
Most commands are available as tkinter
or tkinter.ttk
classes.Change ‘8.6’ to match the version of your Tcl/Tk installation.
Recent Tcl/Tk manuals on www.tcl.tk.
The Tk/Tcl development is largely taking place at ActiveState.
Book by John Ousterhout, the inventor of Tcl.
Brent Welch’s encyclopedic book.
Tkinter Modules¶
Most of the time, tkinter
is all you really need, but a number ofadditional modules are available as well. The Tk interface is located in abinary module named _tkinter
. This module contains the low-levelinterface to Tk, and should never be used directly by application programmers.It is usually a shared library (or DLL), but might in some cases be staticallylinked with the Python interpreter.
In addition to the Tk interface module, tkinter
includes a number ofPython modules, tkinter.constants
being one of the most important.Importing tkinter
will automatically import tkinter.constants
,so, usually, to use Tkinter all you need is a simple import statement:
Or, more often:
tkinter.
Tk
(screenName=None, baseName=None, className='Tk', useTk=1)¶The Tk
class is instantiated without arguments. This creates a toplevelwidget of Tk which usually is the main window of an application. Each instancehas its own associated Tcl interpreter.
tkinter.
Tcl
(screenName=None, baseName=None, className='Tk', useTk=0)¶The Tcl()
function is a factory function which creates an object much likethat created by the Tk
class, except that it does not initialize the Tksubsystem. This is most often useful when driving the Tcl interpreter in anenvironment where one doesn’t want to create extraneous toplevel windows, orwhere one cannot (such as Unix/Linux systems without an X server). An objectcreated by the Tcl()
object can have a Toplevel window created (and the Tksubsystem initialized) by calling its loadtk()
method.
Other modules that provide Tk support include:
tkinter.scrolledtext
Text widget with a vertical scroll bar built in.
tkinter.colorchooser
Dialog to let the user choose a color.
tkinter.commondialog
Base class for the dialogs defined in the other modules listed here.
tkinter.filedialog
Common dialogs to allow the user to specify a file to open or save.
tkinter.font
Utilities to help work with fonts.
tkinter.messagebox
Access to standard Tk dialog boxes.
tkinter.simpledialog
Basic dialogs and convenience functions.
tkinter.dnd
Drag-and-drop support for tkinter
. This is experimental and shouldbecome deprecated when it is replaced with the Tk DND.
turtle
Turtle graphics in a Tk window.
Tkinter Life Preserver¶
This section is not designed to be an exhaustive tutorial on either Tk orTkinter. Rather, it is intended as a stop gap, providing some introductoryorientation on the system.
Credits:
Tk was written by John Ousterhout while at Berkeley.
Tkinter was written by Steen Lumholt and Guido van Rossum.
This Life Preserver was written by Matt Conway at the University of Virginia.
The HTML rendering, and some liberal editing, was produced from a FrameMakerversion by Ken Manheimer.
Fredrik Lundh elaborated and revised the class interface descriptions, to getthem current with Tk 4.2.
Mike Clarkson converted the documentation to LaTeX, and compiled the UserInterface chapter of the reference manual.
How To Use This Section¶
This section is designed in two parts: the first half (roughly) coversbackground material, while the second half can be taken to the keyboard as ahandy reference.
When trying to answer questions of the form “how do I do blah”, it is often bestto find out how to do “blah” in straight Tk, and then convert this back into thecorresponding tkinter
call. Python programmers can often guess at thecorrect Python command by looking at the Tk documentation. This means that inorder to use Tkinter, you will have to know a little bit about Tk. This documentcan’t fulfill that role, so the best we can do is point you to the bestdocumentation that exists. Here are some hints:
The authors strongly suggest getting a copy of the Tk man pages.Specifically, the man pages in the
manN
directory are most useful.Theman3
man pages describe the C interface to the Tk library and thusare not especially helpful for script writers.Addison-Wesley publishes a book called Tcl and the Tk Toolkit by JohnOusterhout (ISBN 0-201-63337-X) which is a good introduction to Tcl and Tk forthe novice. The book is not exhaustive, and for many details it defers to theman pages.
tkinter/__init__.py
is a last resort for most, but can be a goodplace to go when nothing else makes sense.
A Simple Hello World Program¶
A (Very) Quick Look at Tcl/Tk¶
The class hierarchy looks complicated, but in actual practice, applicationprogrammers almost always refer to the classes at the very bottom of thehierarchy.
Notes:
These classes are provided for the purposes of organizing certain functionsunder one namespace. They aren’t meant to be instantiated independently.
The
Tk
class is meant to be instantiated only once in an application.Application programmers need not instantiate one explicitly, the system createsone whenever any of the other classes are instantiated.The
Widget
class is not meant to be instantiated, it is meant onlyfor subclassing to make “real” widgets (in C++, this is called an ‘abstractclass’).
To make use of this reference material, there will be times when you will needto know how to read short passages of Tk and how to identify the various partsof a Tk command. (See section Mapping Basic Tk into Tkinter for thetkinter
equivalents of what’s below.)
Tk scripts are Tcl programs. Like all Tcl programs, Tk scripts are just listsof tokens separated by spaces. A Tk widget is just its class, the optionsthat help configure it, and the actions that make it do useful things.
To make a widget in Tk, the command is always of the form:
denotes which kind of widget to make (a button, a label, a menu…)
is the new name for this widget. All names in Tk must be unique. To helpenforce this, widgets in Tk are named with pathnames, just like files in afile system. The top level widget, the root, is called .
(period) andchildren are delimited by more periods. For example,.myApp.controlPanel.okButton
might be the name of a widget.
configure the widget’s appearance and in some cases, its behavior. The optionscome in the form of a list of flags and values. Flags are preceded by a ‘-‘,like Unix shell command flags, and values are put in quotes if they are morethan one word.
For example:
Once created, the pathname to the widget becomes a new command. This newwidget command is the programmer’s handle for getting the new widget toperform some action. In C, you’d express this as someAction(fred,someOptions), in C++, you would express this as fred.someAction(someOptions),and in Tk, you say:
Note that the object name, .fred
, starts with a dot.
As you’d expect, the legal values for someAction will depend on the widget’sclass: .freddisable
works if fred is a button (fred gets greyed out), butdoes not work if fred is a label (disabling of labels is not supported in Tk).
The legal values of someOptions is action dependent. Some actions, likedisable
, require no arguments, others, like a text-entry box’s delete
command, would need arguments to specify what range of text to delete.
Mapping Basic Tk into Tkinter¶
Class commands in Tk correspond to class constructors in Tkinter.
The master of an object is implicit in the new name given to it at creationtime. In Tkinter, masters are specified explicitly.
The configuration options in Tk are given in lists of hyphened tags followed byvalues. In Tkinter, options are specified as keyword-arguments in the instanceconstructor, and keyword-args for configure calls or as instance indices, indictionary style, for established instances. See sectionSetting Options on setting options.
In Tk, to perform an action on a widget, use the widget name as a command, andfollow it with an action name, possibly with arguments (options). In Tkinter,you call methods on the class instance to invoke actions on the widget. Theactions (methods) that a given widget can perform are listed intkinter/__init__.py
.
To give a widget to the packer (geometry manager), you call pack with optionalarguments. In Tkinter, the Pack class holds all this functionality, and thevarious forms of the pack command are implemented as methods. All widgets intkinter
are subclassed from the Packer, and so inherit all the packingmethods. See the tkinter.tix
module documentation for additionalinformation on the Form geometry manager.
How Tk and Tkinter are Related¶
From the top down:
A Python application makes a tkinter
call.
This call (say, for example, creating a button widget), is implemented inthe tkinter
package, which is written in Python. This Pythonfunction will parse the commands and the arguments and convert them into aform that makes them look as if they had come from a Tk script instead ofa Python script.
These commands and their arguments will be passed to a C function in the_tkinter
- note the underscore - extension module.
This C function is able to make calls into other C modules, including the Cfunctions that make up the Tk library. Tk is implemented in C and some Tcl.The Tcl part of the Tk widgets is used to bind certain default behaviors towidgets, and is executed once at the point where the Python tkinter
package is imported. (The user never sees this stage).
The Tk part of the Tk Widgets implement the final mapping to …
the Xlib library to draw graphics on the screen.
Handy Reference¶
Setting Options¶
Options control things like the color and border width of a widget. Options canbe set in three ways:
- At object creation time, using keyword arguments
- After object creation, treating the option name like a dictionary index
- Use the config() method to update multiple attrs subsequent to object creation
For a complete explanation of a given option and its behavior, see the Tk manpages for the widget in question.
Note that the man pages list “STANDARD OPTIONS” and “WIDGET SPECIFIC OPTIONS”for each widget. The former is a list of options that are common to manywidgets, the latter are the options that are idiosyncratic to that particularwidget. The Standard Options are documented on the options(3) manpage.
No distinction between standard and widget-specific options is made in thisdocument. Some options don’t apply to some kinds of widgets. Whether a givenwidget responds to a particular option depends on the class of the widget;buttons have a command
option, labels do not.
The options supported by a given widget are listed in that widget’s man page, orcan be queried at runtime by calling the config()
method withoutarguments, or by calling the keys()
method on that widget. The returnvalue of these calls is a dictionary whose key is the name of the option as astring (for example, 'relief'
) and whose values are 5-tuples.
Some options, like bg
are synonyms for common options with long names(bg
is shorthand for “background”). Passing the config()
method the nameof a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passedback will contain the name of the synonym and the “real” option (such as('bg','background')
).
Index | Meaning | Example |
---|---|---|
0 | option name |
|
1 | option name for database lookup |
|
2 | option class for databaselookup |
|
3 | default value |
|
4 | current value |
|
Example:
Of course, the dictionary printed will include all the options available andtheir values. This is meant only as an example.
The Packer¶
The packer is one of Tk’s geometry-management mechanisms. Geometry managersare used to specify the relative positioning of the positioning of widgetswithin their container - their mutual master. In contrast to the morecumbersome placer (which is used less commonly, and we do not cover here), thepacker takes qualitative relationship specification - above, to the left of,filling, etc - and works everything out to determine the exact placementcoordinates for you.
The size of any master widget is determined by the size of the “slave widgets”inside. The packer is used to control where slave widgets appear inside themaster into which they are packed. You can pack widgets into frames, and framesinto other frames, in order to achieve the kind of layout you desire.Additionally, the arrangement is dynamically adjusted to accommodate incrementalchanges to the configuration, once it is packed.
Note that widgets do not appear until they have had their geometry specifiedwith a geometry manager. It’s a common early mistake to leave out the geometryspecification, and then be surprised when the widget is created but nothingappears. A widget will appear only after it has had, for example, the packer’spack()
method applied to it.
The pack() method can be called with keyword-option/value pairs that controlwhere the widget is to appear within its container, and how it is to behave whenthe main application window is resized. Here are some examples:
Packer Options¶
For more extensive information on the packer and the options that it can take,see the man pages and page 183 of John Ousterhout’s book.
Anchor type. Denotes where the packer is to place each slave in its parcel.
Boolean, 0
or 1
.
Legal values: 'x'
, 'y'
, 'both'
, 'none'
.
A distance - designating internal padding on each side of the slave widget.
A distance - designating external padding on each side of the slave widget.
Legal values are: 'left'
, 'right'
, 'top'
, 'bottom'
.
Coupling Widget Variables¶
The current-value setting of some widgets (like text entry widgets) can beconnected directly to application variables by using special options. Theseoptions are variable
, textvariable
, onvalue
, offvalue
, andvalue
. This connection works both ways: if the variable changes for anyreason, the widget it’s connected to will be updated to reflect the new value.
Unfortunately, in the current implementation of tkinter
it is notpossible to hand over an arbitrary Python variable to a widget through avariable
or textvariable
option. The only kinds of variables for whichthis works are variables that are subclassed from a class called Variable,defined in tkinter
.
There are many useful subclasses of Variable already defined:StringVar
, IntVar
, DoubleVar
, andBooleanVar
. To read the current value of such a variable, call theget()
method on it, and to change its value you call the set()
method. If you follow this protocol, the widget will always track the value ofthe variable, with no further intervention on your part.
For example:
The Window Manager¶
In Tk, there is a utility command, wm
, for interacting with the windowmanager. Options to the wm
command allow you to control things like titles,placement, icon bitmaps, and the like. In tkinter
, these commands havebeen implemented as methods on the Wm
class. Toplevel widgets aresubclassed from the Wm
class, and so can call the Wm
methodsdirectly.
To get at the toplevel window that contains a given widget, you can often justrefer to the widget’s master. Of course if the widget has been packed inside ofa frame, the master won’t represent a toplevel window. To get at the toplevelwindow that contains an arbitrary widget, you can call the _root()
method.This method begins with an underscore to denote the fact that this function ispart of the implementation, and not an interface to Tk functionality.
Here are some examples of typical usage:
Tk Option Data Types¶
Legal values are points of the compass: 'n'
, 'ne'
, 'e'
, 'se'
,'s'
, 'sw'
, 'w'
, 'nw'
, and also 'center'
.
There are eight built-in, named bitmaps: 'error'
, 'gray25'
,'gray50'
, 'hourglass'
, 'info'
, 'questhead'
, 'question'
,'warning'
. To specify an X bitmap filename, give the full path to the file,preceded with an @
, as in '@/usr/contrib/bitmap/gumby.bit'
.
You can pass integers 0 or 1 or the strings 'yes'
or 'no'
.
This is any Python function that takes no arguments. For example:
Colors can be given as the names of X colors in the rgb.txt file, or as stringsrepresenting RGB values in 4 bit: '#RGB'
, 8 bit: '#RRGGBB'
, 12 bit”'#RRRGGGBBB'
, or 16 bit '#RRRRGGGGBBBB'
ranges, where R,G,B hererepresent any legal hex digit. See page 160 of Ousterhout’s book for details.
The standard X cursor names from cursorfont.h
can be used, without theXC_
prefix. For example to get a hand cursor (XC_hand2
), use thestring 'hand2'
. You can also specify a bitmap and mask file of your own.See page 179 of Ousterhout’s book.
Screen distances can be specified in either pixels or absolute distances.Pixels are given as numbers and absolute distances as strings, with the trailingcharacter denoting units: c
for centimetres, i
for inches, m
formillimetres, p
for printer’s points. For example, 3.5 inches is expressedas '3.5i'
.
Tk uses a list font name format, such as {courier10bold}
. Font sizes withpositive numbers are measured in points; sizes with negative numbers aremeasured in pixels.
This is a string of the form widthxheight
, where width and height aremeasured in pixels for most widgets (in characters for widgets displaying text).For example: fred['geometry']='200x100'
.
Legal values are the strings: 'left'
, 'center'
, 'right'
, and'fill'
.
This is a string with four space-delimited elements, each of which is a legaldistance (see above). For example: '2345'
and '3i2i4.5i2i'
and'3c2c4c10.43c'
are all legal regions.
Determines what the border style of a widget will be. Legal values are:'raised'
, 'sunken'
, 'flat'
, 'groove'
, and 'ridge'
.
This is almost always the set()
method of some scrollbar widget, but canbe any widget method that takes a single argument.
Must be one of: 'none'
, 'char'
, or 'word'
.
Bindings and Events¶
The bind method from the widget command allows you to watch for certain eventsand to have a callback function trigger when that event type occurs. The formof the bind method is:
where:
is a string that denotes the target kind of event. (See the bind man page andpage 201 of John Ousterhout’s book for details).
is a Python function, taking one argument, to be invoked when the event occurs.An Event instance will be passed as the argument. (Functions deployed this wayare commonly known as callbacks.)
is optional, either '
or '+'
. Passing an empty string denotes thatthis binding is to replace any other bindings that this event is associatedwith. Passing a '+'
means that this function is to be added to the listof functions bound to this event type.
For example:
Notice how the widget field of the event is being accessed in theturn_red()
callback. This field contains the widget that caught the Xevent. The following table lists the other event fields you can access, and howthey are denoted in Tk, which can be useful when referring to the Tk man pages.
Tk | Tkinter Event Field | Tk | Tkinter Event Field |
---|---|---|---|
%f | focus | %A | char |
%h | height | %E | send_event |
%k | keycode | %K | keysym |
%s | state | %N | keysym_num |
%t | time | %T | type |
%w | width | %W | widget |
%x | x | %X | x_root |
%y | y | %Y | y_root |
The index Parameter¶
A number of widgets require “index” parameters to be passed. These are used topoint at a specific place in a Text widget, or to particular characters in anEntry widget, or to particular menu items in a Menu widget.
Entry widgets have options that refer to character positions in the text beingdisplayed. You can use these tkinter
functions to access these specialpoints in text widgets:
The index notation for Text widgets is very rich and is best described in the Tkman pages.
Some options and methods for menus manipulate specific menu entries. Anytime amenu index is needed for an option or a parameter, you may pass in:
an integer which refers to the numeric position of the entry in the widget,counted from the top, starting with 0;
the string
'active'
, which refers to the menu position that is currentlyunder the cursor;the string
'last'
which refers to the last menu item;An integer preceded by
@
, as in@6
, where the integer is interpretedas a y pixel coordinate in the menu’s coordinate system;the string
'none'
, which indicates no menu entry at all, most often usedwith menu.activate() to deactivate all entries, and finally,a text string that is pattern matched against the label of the menu entry, asscanned from the top of the menu to the bottom. Note that this index type isconsidered after all the others, which means that matches for menu itemslabelled
last
,active
, ornone
may be interpreted as the aboveliterals, instead.
Images¶
Images of different formats can be created through the corresponding subclassof tkinter.Image
:
BitmapImage
for images in XBM format.PhotoImage
for images in PGM, PPM, GIF and PNG formats. The latteris supported starting with Tk 8.6.
Either type of image is created through either the file
or the data
option (other options are available as well).
The image object can then be used wherever an image
option is supported bysome widget (e.g. labels, buttons, menus). In these cases, Tk will not keep areference to the image. When the last Python reference to the image object isdeleted, the image data is deleted as well, and Tk will display an empty boxwherever the image was used.
See also
The Pillow package adds support forformats such as BMP, JPEG, TIFF, and WebP, among others.
File Handlers¶
Tk allows you to register and unregister a callback function which will becalled from the Tk mainloop when I/O is possible on a file descriptor.Only one handler may be registered per file descriptor. Example code:
This feature is not available on Windows.
Since you don’t know how many bytes are available for reading, you may notwant to use the BufferedIOBase
or TextIOBase
read()
or readline()
methods,since these will insist on reading a predefined number of bytes.For sockets, the recv()
orrecvfrom()
methods will work fine; for other files,use raw reads or os.read(file.fileno(),maxbytecount)
.
Widget.tk.
createfilehandler
(file, mask, func)¶Registers the file handler callback function func. The file argumentmay either be an object with a fileno()
method (such asa file or socket object), or an integer file descriptor. The maskargument is an ORed combination of any of the three constants below.The callback is called as follows:
Widget.tk.
deletefilehandler
(file)¶Unregisters a file handler.
tkinter.
READABLE
¶tkinter.
WRITABLE
¶tkinter.
EXCEPTION
¶Constants used in the mask arguments.