tkinter.ttk --- Tk 主題化小工具

原始碼:Lib/tkinter/ttk.py


Thetkinter.ttk module provides access to the Tk themed widget set,introduced in Tk 8.5. It provides additional benefits including anti-aliased fontrendering under X11 and window transparency (requiring a compositionwindow manager on X11).

The basic idea fortkinter.ttk is to separate, to the extent possible,the code implementing a widget's behavior from the code implementing itsappearance.

也參考

Tk Widget Styling Support

A document introducing theming support for Tk

使用 Ttk

To start using Ttk, import its module:

fromtkinterimportttk

To override the basic Tk widgets, the import should follow the Tk import:

fromtkinterimport*fromtkinter.ttkimport*

That code causes severaltkinter.ttk widgets (Button,Checkbutton,Entry,Frame,Label,LabelFrame,Menubutton,PanedWindow,Radiobutton,Scale andScrollbar) 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 thettk.Style classfor improved styling effects.

也參考

Converting existing applications to use Tile widgets

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, andSpinbox.The other six are new:Combobox,Notebook,Progressbar,Separator,Sizegrip andTreeview. And all them are subclasses ofWidget.

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:

l1=tkinter.Label(text="Test",fg="black",bg="white")l2=tkinter.Label(text="Test",fg="black",bg="white")

Ttk code:

style=ttk.Style()style.configure("BW.TLabel",foreground="black",background="white")l1=ttk.Label(text="Test",style="BW.TLabel")l2=ttk.Label(text="Test",style="BW.TLabel")

For more information aboutTtkStyling, see theStyle classdocumentation.

Widget

ttk.Widget defines standard options and methods supported by Tkthemed widgets and is not supposed to be directly instantiated.

標準選項

All thettk Widgets accept the following options:

選項

描述

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.

選項

描述

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 methodScrollbar.set() of some scrollbar. This will causethe scrollbar to be updated whenever the view in thewindow changes.

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.

選項

描述

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 byStyle.map(), specifying different imagesto use when the widget is in a particular state or acombination of states. All images in the list should havethe 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:

  • text: display text only

  • image: display image only

  • top, bottom, left, right: display image above, below,left of, or right of the text, respectively.

  • none: the default. display the image if present,otherwise the text.

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.

相容性選項

選項

描述

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 theWidget.state() method does notaffect this option.

Widget States

The widget state is a bitmap of independent state flags.

旗標

描述

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. Thebackground 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, thettk.Widget supports themethodstkinter.Widget.cget() andtkinter.Widget.configure().

classtkinter.ttk.Widget
identify(x,y)

Returns the name of the element at positionxy, or the empty stringif the point does not lie within any element.

x andy are pixel coordinates relative to the widget.

instate(statespec,callback=None,*args,**kw)

Test the widget's state. If a callback is not specified, returnsTrueif the widget state matchesstatespec andFalse otherwise. If callbackis specified then it is called with args if widget state matchesstatespec.

state(statespec=None)

Modify or inquire widget state. Ifstatespec is specified, sets thewidget state according to it and return a newstatespec indicatingwhich flags were changed. Ifstatespec is not specified, returnsthe currently enabled state flags.

statespec will usually be a list or a tuple.

Combobox

Thettk.Combobox widget combines a text field with a pop-down list ofvalues. This widget is a subclass ofEntry.

Besides the methods inherited fromWidget:Widget.cget(),Widget.configure(),Widget.identify(),Widget.instate()andWidget.state(), and the following inherited fromEntry:Entry.bbox(),Entry.delete(),Entry.icursor(),Entry.index(),Entry.insert(),Entry.selection(),Entry.xview(), it has some other methods, described atttk.Combobox.

選項

This widget accepts the following specific options:

選項

描述

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.Seetkinter.StringVar.

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

classtkinter.ttk.Combobox
current(newindex=None)

Ifnewindex is specified, sets the combobox value to the elementpositionnewindex. 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 tovalue.

Spinbox

Thettk.Spinbox widget is attk.Entry enhanced with incrementand decrement arrows. It can be used for numbers or lists of string values.This widget is a subclass ofEntry.

Besides the methods inherited fromWidget:Widget.cget(),Widget.configure(),Widget.identify(),Widget.instate()andWidget.state(), and the following inherited fromEntry:Entry.bbox(),Entry.delete(),Entry.icursor(),Entry.index(),Entry.insert(),Entry.xview(),it has some other methods, described atttk.Spinbox.

選項

This widget accepts the following specific options:

選項

描述

from

Float value. If set, this is the minimum value towhich the decrement button will decrement. Must bespelled asfrom_ when used as an argument, sincefrom is a Python keyword.

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. IfTrue, increment and decrementbuttons will cycle from theto value to thefrom value or thefrom value to thetovalue, respectively.

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

classtkinter.ttk.Spinbox
get()

Returns the current value of the spinbox.

set(value)

Sets the value of the spinbox tovalue.

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.

選項

This widget accepts the following specific options:

選項

描述

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:

選項

描述

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 thegrid() geometry manager.

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 inWidget.

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 ifNotebook.enable_traversal() iscalled.

Tab Identifiers

The tab_id present in several methods ofttk.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 forNotebook.index())

虛擬事件

This widget generates a<<NotebookTabChanged>> virtual event after a newtab is selected.

ttk.Notebook

classtkinter.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.

可用的選項清單請見Tab Options

forget(tab_id)

Removes the tab specified bytab_id, unmaps and unmanages theassociated window.

hide(tab_id)

Hides the tab specified bytab_id.

The tab will not be displayed, but the associated window remainsmanaged by the notebook and its configuration remembered. Hidden tabsmay be restored with theadd() command.

identify(x,y)

Returns the name of the tab element at positionx,y, or the emptystring if none.

index(tab_id)

Returns the numeric index of the tab specified bytab_id, or the totalnumber of tabs iftab_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. Ifchild is already managed by the notebook, moves it tothe specified position.

可用的選項清單請見Tab Options

select(tab_id=None)

Selects the specifiedtab_id.

The associated child window will be displayed, and thepreviously selected window (if different) is unmapped. Iftab_id isomitted, returns the widget name of the currently selected pane.

tab(tab_id,option=None,**kw)

Query or modify the options of the specifictab_id.

Ifkw is not given, returns a dictionary of the tab option values. Ifoption is specified, returns the value of thatoption. 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: whereK 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

Thettk.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.

選項

This widget accepts the following specific options:

選項

描述

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

"determinate" 與 "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 modulomaximum;that is, the progress bar completes one "cycle" when its valueincreases bymaximum.

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

classtkinter.ttk.Progressbar
start(interval=None)

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

step(amount=None)

Increments the progress bar's value byamount.

amount defaults to 1.0 if omitted.

stop()

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

Separator

Thettk.Separator widget displays a horizontal or vertical separatorbar.

It has no other methods besides the ones inherited fromttk.Widget.

選項

This widget accepts the following specific option:

選項

描述

orient

One of "horizontal" or "vertical". Specifies the orientation ofthe separator.

Sizegrip

Thettk.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 fromttk.Widget.

Platform-specific notes

  • On macOS, toplevel windows automatically include a built-in size gripby default. Adding aSizegrip 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. ....), theSizegrip widget willnot resize the window.

  • This widget supports only "southeast" resizing.

Treeview

Thettk.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 optiondisplaycolumns. The tree widget can also display columnheadings. Columns may be accessed by number or symbolic names listed in thewidget option columns. SeeColumn 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 inScrollable Widget Options and the methodsTreeview.xview() andTreeview.yview().

選項

This widget accepts the following specific options:

選項

描述

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.

  • tree: display tree labels in column #0.

  • headings: display the heading row.

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.

選項

描述

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'schildren should be displayed or hidden.

tags

A list of tags associated with this item.

Tag Options

The following options may be specified on tags:

選項

描述

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.

註解:

  • 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.

虛擬事件

The Treeview widget generates the following virtual events.

事件

描述

<<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.

TheTreeview.focus() andTreeview.selection() methods can be usedto determine the affected item or items.

ttk.Treeview

classtkinter.ttk.Treeview
bbox(item,column=None)

Returns the bounding box (relative to the treeview widget's window) ofthe specifieditem in the form (x, y, width, height).

Ifcolumn 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 toitem.

Ifitem is not specified, returns root children.

set_children(item,*newchildren)

Replacesitem's child withnewchildren.

Children present initem that are not present innewchildren aredetached from the tree. No items innewchildren may be an ancestor ofitem. Note that not specifyingnewchildren results in detachingitem's children.

column(column,option=None,**kw)

Query or modify the options for the specifiedcolumn.

Ifkw is not given, returns a dict of the column option values. Ifoption is specified then the value for thatoption is returned.Otherwise, sets the options to the corresponding values.

有效的選項/值為:

id

回傳欄位名稱。這是唯讀選項。

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 specifieditems and all their descendants.

The root item may not be deleted.

detach(*items)

Unlinks all of the specifieditems 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)

ReturnsTrue if the specifieditem is present in the tree.

focus(item=None)

Ifitem is specified, sets the focus item toitem. Otherwise, returnsthe current focus item, or '' if there is none.

heading(column,option=None,**kw)

Query or modify the heading options for the specifiedcolumn.

Ifkw is not given, returns a dict of the heading option values. Ifoption is specified then the value for thatoption is returned.Otherwise, sets the options to the corresponding values.

有效的選項/值為:

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 specifiedcomponent under the point givenbyx andy, or the empty string if no suchcomponent is present atthat position.

identify_row(y)

Returns the item ID of the item at positiony.

identify_column(x)

Returns the data column identifier of the cell at positionx.

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 positionx,y.

Availability: Tk 8.6.

index(item)

Returns the integer index ofitem 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.Ifindex is less than or equal to zero, the new node is inserted atthe beginning; ifindex is greater than or equal to the current numberof children, it is inserted at the end. Ifiid is specified, it is usedas the item identifier;iid must not already exist in the tree.Otherwise, a new unique identifier is generated.

可用的選項清單請見Item Options

item(item,option=None,**kw)

Query or modify the options for the specifieditem.

If no options are given, a dict with options/values for the item isreturned.Ifoption is specified then the value for that option is returned.Otherwise, sets the options to the corresponding values as given bykw.

move(item,parent,index)

Movesitem to positionindex inparent's list of children.

It is illegal to move an item under one of its descendants. Ifindex 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. Ifitemwas detached it is reattached.

next(item)

Returns the identifier ofitem's next sibling, or '' ifitem is thelast child of its parent.

parent(item)

Returns the ID of the parent ofitem, or '' ifitem is at the toplevel of the hierarchy.

prev(item)

Returns the identifier ofitem's previous sibling, or '' ifitem isthe first child of its parent.

reattach(item,parent,index)

一個Treeview.move() 的別名。

see(item)

確保item 是可見的。

Sets all ofitem's ancestors open option toTrue, and scrolls thewidget if necessary so thatitem is within the visible portion ofthe tree.

selection()

Returns a tuple of selected items.

在 3.8 版的變更:selection() no longer takes arguments. For changing the selectionstate use the following selection methods.

selection_set(*items)

items becomes the new selection.

在 3.6 版的變更:items can be passed as separate arguments, not just as a single tuple.

selection_add(*items)

items 加入選擇。

在 3.6 版的變更:items can be passed as separate arguments, not just as a single tuple.

selection_remove(*items)

從選擇中移除items

在 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 initems.

在 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 thespecifieditem. With two arguments, returns the current value of thespecifiedcolumn. With three arguments, sets the value of givencolumn in givenitem to the specifiedvalue.

tag_bind(tagname,sequence=None,callback=None)

Bind a callback for the given eventsequence to the tagtagname.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 specifiedtagname.

Ifkw is not given, returns a dict of the option settings fortagname. Ifoption is specified, returns the value for thatoptionfor the specifiedtagname. Otherwise, sets the options to thecorresponding values for the giventagname.

tag_has(tagname,item=None)

Ifitem is specified, returns 1 or 0 depending on whether the specifieditem has the giventagname. 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 inttk 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()).

也參考

Tcl'2004 conference presentation

This document explains how the theme engine works

classtkinter.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) instyle.

Each key inkw 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:

fromtkinterimportttkimporttkinterroot=tkinter.Tk()ttk.Style().configure("TButton",padding=6,relief="flat",background="#ccc")btn=ttk.Button(text="Sample")btn.pack()root.mainloop()
map(style,query_opt=None,**kw)

Query or sets dynamic values of the specified option(s) instyle.

Each key inkw 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:

importtkinterfromtkinterimportttkroot=tkinter.Tk()style=ttk.Style()style.map("C.TButton",foreground=[('pressed','red'),('active','blue')],background=[('pressed','!disabled','black'),('active','white')])colored_btn=ttk.Button(text="Test",style="C.TButton").pack()root.mainloop()

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 foroption instyle.

Ifstate is specified, it is expected to be a sequence of one or morestates. If thedefault 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:

fromtkinterimportttkprint(ttk.Style().lookup("TButton","font"))
layout(style,layoutspec=None)

Define the widget layout for givenstyle. Iflayoutspec 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 inLayouts.

To understand the format, see the following example (it is notintended to do anything useful):

fromtkinterimportttkimporttkinterroot=tkinter.Tk()style=ttk.Style()style.layout("TMenubutton",[("Menubutton.background",None),("Menubutton.button",{"children":[("Menubutton.focus",{"children":[("Menubutton.padding",{"children":[("Menubutton.label",{"side":"left","expand":1})]})]})]}),])mbtn=ttk.Menubutton(text='Text')mbtn.pack()root.mainloop()
element_create(elementname,etype,*args,**kw)

Create a new element in the current theme, of the givenetype which isexpected to be either "image", "from" or "vsapi".The latter is only available in Tk 8.6 on Windows.

If "image" is used,args should contain the default image name followedby statespec/value pairs (this is the imagespec), andkw 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.

範例:

img1=tkinter.PhotoImage(master=root,file='button.png')img1=tkinter.PhotoImage(master=root,file='button-pressed.png')img1=tkinter.PhotoImage(master=root,file='button-active.png')style=ttk.Style(root)style.element_create('Button.button','image',img1,('pressed',img2),('active',img3),border=(2,4),sticky='we')

If "from" is used as the value ofetype,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.

範例:

style=ttk.Style(root)style.element_create('plain.background','from','default')

If "vsapi" is used as the value ofetype,element_create()will create a new element in the current theme whose visual appearanceis drawn using the Microsoft Visual Styles API which is responsiblefor the themed styles on Windows XP and Vista.args is expected to contain the Visual Styles class and part asgiven in the Microsoft documentation followed by an optional sequenceof tuples of ttk states and the corresponding Visual Styles API statevalue.kw may have the following options:

padding=padding

Specify the element's interior padding.padding is a list of up to four integers specifying the left,top, right and bottom padding quantities respectively.If fewer than four elements are specified, bottom defaults to top,right defaults to left, and top defaults to left.In other words, a list of three numbers specify the left, vertical,and right padding; a list of two numbers specify the horizontaland the vertical padding; a single number specifies the samepadding all the way around the widget.This option may not be mixed with any other options.

margins=padding

Specifies the elements exterior padding.padding is a list of up to four integers specifying the left, top,right and bottom padding quantities respectively.This option may not be mixed with any other options.

width=width

Specifies the width for the element.If this option is set then the Visual Styles API will not be queriedfor the recommended size or the part.If this option is set thenheight should also be set.Thewidth andheight options cannot be mixed with thepaddingormargins options.

height=height

Specifies the height of the element.See the comments forwidth.

範例:

style=ttk.Style(root)style.element_create('pin','vsapi','EXPLORERBAR',3,[('pressed','!selected',3),('active','!selected',2),('pressed','selected',6),('active','selected',5),('selected',4),('',1)])style.layout('Explorer.Pin',[('Explorer.Pin.pin',{'sticky':'news'})])pin=ttk.Checkbutton(style='Explorer.Pin')pin.pack(expand=True,fill='both')

在 3.13 版的變更:Added support of the "vsapi" element factory.

element_names()

Returns the list of elements defined in the current theme.

element_options(elementname)

Returns the list ofelementname's options.

theme_create(themename,parent=None,settings=None)

Create a new theme.

It is an error ifthemename already exists. Ifparent is specified,the new theme will inherit styles, elements and layouts from the parenttheme. Ifsettings are present they are expected to have the samesyntax used fortheme_settings().

theme_settings(themename,settings)

Temporarily sets the current theme tothemename, apply specifiedsettings and then restore the previous theme.

Each key insettings 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:

fromtkinterimportttkimporttkinterroot=tkinter.Tk()style=ttk.Style()style.theme_settings("default",{"TCombobox":{"configure":{"padding":5},"map":{"background":[("active","green2"),("!disabled","green4")],"fieldbackground":[("!disabled","green3")],"foreground":[("focus","OliveDrab1"),("!disabled","OliveDrab2")]}}})combo=ttk.Combobox().pack()root.mainloop()
theme_names()

回傳所有已知的主題。

theme_use(themename=None)

Ifthemename is not given, returns the theme in use. Otherwise, setsthe current theme tothemename, refreshes all widgets and emits a<<ThemeChanged>> event.

Layouts

A layout can be justNone, 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.

有效的選項/值為:

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 或 1

If set to 1, causes the element and all of its descendants to be treated asa single element for the purposes ofWidget.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 aLayout.