tkinter.ttkTk themed widgetsTk主题小部件

Source code: Lib/tkinter/ttk.py


The tkinter.ttk module provides access to the Tk themed widget set, introduced in Tk 8.5. tkinter.ttk模块提供对Tk 8.5中引入的Tk主题小部件集的访问。If Python has not been compiled against Tk 8.5, this module can still be accessed if Tile has been installed. 如果尚未针对Tk 8.5编译Python,那么如果安装了Tile,仍然可以访问此模块。The former method using Tk 8.5 provides additional benefits including anti-aliased font rendering under X11 and window transparency (requiring a composition window manager on X11).使用Tk 8.5的前一种方法提供了其他好处,包括X11下的抗锯齿字体渲染和窗口透明度(需要X11上的合成窗口管理器)。

The basic idea for tkinter.ttk is to separate, to the extent possible, the code implementing a widget’s behavior from the code implementing its appearance.tkinter.ttk的基本思想是尽可能地将实现小部件行为的代码与实现其外观的代码分离开来。

See also参阅

Tk Widget Styling SupportTk小部件样式支持

A document introducing theming support for Tk介绍Tk主题化支持的文档

Using 使用Ttk

To start using Ttk, import its module:要开始使用Ttk,请导入其模块:

from tkinter import ttk

To override the basic Tk widgets, the import should follow the Tk import:要覆盖基本的Tk小部件,导入应遵循Tk导入:

from tkinter import *
from tkinter.ttk import *

That code causes several tkinter.ttk widgets (Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar) to automatically replace the Tk widgets.该代码导致几个tkinter.ttk小部件(ButtonCheckbuttonEntryFrameLabelLabelFrameMenubuttonPanedWindowRadiobuttonScaleScrollbar)自动替换Tk小部件。

This has the direct benefit of using the new widgets which gives a better look and feel across platforms; however, the replacement widgets are not completely compatible. 这有一个直接的好处,就是使用新的小部件,可以在不同平台上提供更好的外观和感觉;但是,替换小部件并不完全兼容。The main difference is that widget options such as “fg”, “bg” and others related to widget styling are no longer present in Ttk widgets. 主要区别在于,Ttk小部件中不再存在诸如“fg”、“bg”等与小部件样式相关的小部件选项。Instead, use the ttk.Style class for improved styling effects.相反,使用ttkStyle类可以改善造型效果。

See also参阅

Converting existing applications to use Tile widgets将现有应用程序转换为使用平铺小部件

A monograph (using Tcl terminology) about differences typically encountered when moving applications to use the new widgets.一本专著(使用Tcl术语),介绍了在将应用程序移动到使用新窗口小部件时通常会遇到的差异。

Ttk WidgetsTtk小部件

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. Ttk附带了18个小部件,其中12个已经存在于tkinter中:ButtonCheckbuttonEntryFrameLabelLabelFrameMenubuttonPanedWindowRadiobuttonScaleScrollbarSpinboxThe other six are new: Combobox, Notebook, Progressbar, Separator, Sizegrip and Treeview. 另有六个新的小部件:ComboboxNotebookProgressbarSeparatorSizegripTreeviewAnd all them are subclasses of Widget.它们全是Widget的子类。

Using the Ttk widgets gives the application an improved look and feel. 使用Ttk小部件可以改善应用程序的外观。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 about TtkStyling, see the Style class documentation.有关TtkStyling的详细信息,请参阅Style类文档。

Widget小部件

ttk.Widget defines standard options and methods supported by Tk themed widgets and is not supposed to be directly instantiated.定义以Tk为主题的小部件支持的标准选项和方法,不应直接实例化。

Standard Options标准选项

All the ttk Widgets accepts the following options:所有ttk小部件都接受以下选项:

Option选项

Description描述

class

Specifies the window class. 指定窗口类。The class is used when querying the option database for the window’s other options, to determine the default bindtags for the window, and to select the widget’s default layout and style. 该类用于在选项数据库中查询窗口的其他选项,以确定窗口的默认bindtags,并选择小部件的默认布局和样式。This option is read-only, and may only be specified when the window is created.此选项为只读,只能在创建窗口时指定。

cursor

Specifies the mouse cursor to be used for the widget. 指定要用于小部件的鼠标光标。If set to the empty string (the default), the cursor is inherited for the parent widget.如果设置为空字符串(默认值),则会为父窗口小部件继承光标。

takefocus

Determines whether the window accepts the focus during keyboard traversal. 0, 1 or an empty string is returned. 确定窗口在键盘遍历期间是否接受焦点。返回0、1或空字符串。If 0 is returned, it means that the window should be skipped entirely during keyboard traversal. 如果返回0,则表示在键盘遍历期间应完全跳过该窗口。If 1, it means that the window should receive the input focus as long as it is viewable. 如果为1,则表示只要窗口可见,它就应该接收输入焦点。And an empty string means that the traversal scripts make the decision about whether or not to focus on the window.空字符串表示遍历脚本决定是否关注窗口。

style

May be used to specify a custom widget style.可用于指定自定义小部件样式。

Scrollable Widget Options可滚动小部件选项

The following options are supported by widgets that are controlled by a scrollbar.由滚动条控制的小部件支持以下选项。

Option选项

Description描述

xscrollcommand

Used to communicate with horizontal scrollbars.用于与水平滚动条通信。

When the view in the widget’s window change, the widget will generate a Tcl command based on the scrollcommand.当小部件窗口中的视图更改时,小部件将基于scroll命令生成一个Tcl命令。

Usually this option consists of the method Scrollbar.set() of some scrollbar. 通常,此选项由某些scrollbar的方法Scrollbar.set()组成。This will cause the scrollbar to be updated whenever the view in the window changes.这将导致每当窗口中的视图更改时,滚动条都会更新。

yscrollcommand

Used to communicate with vertical scrollbars. 用于与垂直滚动条通信。For some more information, see above.有关更多信息,请参阅上文。

Label Options标签选项

The following options are supported by labels, buttons and other button-like widgets.标签、按钮和其他类似按钮的小部件支持以下选项。

Option选项

Description描述

text

Specifies a text string to be displayed inside the widget.指定要在小部件内显示的文本字符串。

textvariable

Specifies a name whose value will be used in place of the text option resource.指定一个名称,该名称的值将用于替代文本选项资源。

underline

If set, specifies the index (0-based) of a character to underline in the text string. 如果设置,则指定要在文本字符串中加下划线的字符的索引(基于0)。The underline character is used for mnemonic activation.下划线字符用于记忆激活。

image

Specifies an image to display. 指定要显示的图像。This is a list of 1 or more elements. 这是一个包含1个或多个元素的列表。The first element is the default image name. 第一个元素是默认图像名称。The rest of the list if a sequence of statespec/value pairs as defined by Style.map(), specifying different images to use when the widget is in a particular state or a combination of states. 如果是Style.map()定义的状态规范/值对序列,则为列表的其余部分,指定当小部件处于特定状态或状态组合时要使用的不同图像。All images in the list should have the same size.列表中的所有图像应具有相同的大小。

compound

Specifies how to display the image relative to the text, in the case both text and images options are present. 指定在同时存在文本和图像选项的情况下,如何相对于文本显示图像。Valid values are:有效值为:

  • text: display text only:仅显示文本

  • image: display image only:仅显示图像

  • top, bottom, left, righttopbottomleftright: 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, in character widths, to allocate for the text label, if less than zero, specifies a minimum width. 如果大于零,则指定要为文本标签分配的空间大小(以字符宽度为单位),如果小于零,则指定最小宽度。If zero or unspecified, the natural width of the text label is used.如果为零或未指定,则使用文本标签的自然宽度。

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 the widget state, but the Widget.state() method does not affect this option.这是一个只写选项:设置它会更改小部件状态,但Widget.state()方法不会影响此选项。

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 mouse button will cause some action to occur鼠标光标位于小部件上,按下鼠标按钮将导致发生某些操作

disabled

Widget is disabled under program control程序控制下禁用小部件

focus

Widget has keyboard focus小部件具有键盘焦点

pressed

Widget is being pressed正在按下小部件

selected

“On”, “true”, or “current” for things like Checkbuttons and radiobuttons“On”、“true”或“current”表示复选按钮和单选按钮

background

Windows and Mac have a notion of an “active” or foreground window. Windows和Mac有“活动”或前景窗口的概念。The background state is set for widgets in a background window, and cleared for those in the foreground windowbackground状态为背景窗口中的小部件设置,并为前景窗口中的小部件清除

readonly

Widget should not allow user modification小部件不应允许用户修改

alternate

A widget-specific alternate display format特定于小部件的备用显示格式

invalid

The widget’s value is invalid小部件的值无效

A state specification is a sequence of state names, optionally prefixed with an exclamation point indicating that the bit is off.状态规范是一系列状态名称,可以选择在前面加一个感叹号,表示该位已关闭。

ttk.Widget

Besides the methods described below, the ttk.Widget supports the methods tkinter.Widget.cget() and tkinter.Widget.configure().除了下面描述的方法之外,ttk.Widget还支持方法tkinter.Widget.cget()tkinter.Widget.configure()

classtkinter.ttk.Widget
identify(x, y)

Returns the name of the element at position x y, or the empty string if the point does not lie within any element.返回x y位置的元素名称,如果该点不在任何元素内,则返回空字符串。

x and y are pixel coordinates relative to the widget.xy是相对于小部件的像素坐标。

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. 如果未指定回调,则如果小部件状态与statespec匹配,则返回True,否则返回FalseIf callback is specified then it is called with args if widget state matches statespec.如果指定了回调,则如果小部件状态与statespec匹配,则使用参数调用回调。

state(statespec=None)

Modify or inquire widget state. 修改或查询小部件状态。If statespec is specified, sets the widget state according to it and return a new statespec indicating which flags were changed. 如果指定了statespec,则根据它设置小部件状态,并返回一个新的statespec,指示哪些标志已更改。If statespec is not specified, returns the currently-enabled state flags.如果未指定statespec,则返回当前启用的状态标志。

statespec will usually be a list or a tuple.通常是列表或元组。

Combobox组合框

The ttk.Combobox widget combines a text field with a pop-down list of values. ttk.Combobox小部件将文本字段与值的下拉列表相结合。This widget is a subclass of Entry.这个小部件是Entry的一个子类。

Besides the methods inherited from Widget: Widget.cget(), Widget.configure(), Widget.identify(), Widget.instate() and Widget.state(), and the following inherited from Entry: Entry.bbox(), Entry.delete(), Entry.icursor(), Entry.index(), Entry.insert(), Entry.selection(), Entry.xview(), it has some other methods, described at ttk.Combobox.除了继续自Widget的方法(Widget.cget()Widget.configure()Widget.identify()Widget.instate()Widget.state())之外,以下方法继承自EntryEntry.bbox(), Entry.delete()Entry.icursor()Entry.index()Entry.insert()Entry.selection()Entry.xview(),它还有一些其它方法,在ttk.Combobox中描述。

Options选项

This widget accepts the following specific options:此小部件接受以下特定选项:

Option选项

Description描述

exportselection

Boolean value. 布尔值。If set, the widget selection is linked to the Window Manager selection (which can be returned by invoking Misc.selection_get, for example).如果设置,小部件选择将链接到窗口管理器选择(例如,可以通过调用Miscselection_get返回)。

justify

Specifies how the text is aligned within the widget. One of “left”, “center”, or “right”.指定文本在小部件内的对齐方式。“左”、“中”或“右”之一。

height

Specifies the height of the pop-down listbox, in rows.以行为单位指定下拉列表框的高度。

postcommand

A script (possibly registered with Misc.register) that is called immediately before displaying the values. 在显示值之前立即调用的脚本(可能已向Miscregister注册)。It may specify which values to display.它可以指定要显示的值。

state

One of “normal”, “readonly”, or “disabled”. “正常”、“只读”或“禁用”之一。In the “readonly” state, the value may not be edited directly, and the user can only selection of the values from the dropdown list. 在“只读”状态下,不能直接编辑值,用户只能从下拉列表中选择值。In the “normal” state, the text field is directly editable. 在“正常”状态下,文本字段可直接编辑。In the “disabled” state, no interaction is possible.在“禁用”状态下,不可能进行交互。

textvariable

Specifies a name whose value is linked to the widget value. 指定其值链接到小部件值的名称。Whenever the value associated with that name changes, the widget value is updated, and vice versa. 每当与该名称关联的值更改时,小部件值都会更新,反之亦然。See tkinter.StringVar.请参阅tkinter.StringVar

values

Specifies the list of values to display in the drop-down listbox.指定要在下拉列表框中显示的值列表。

width

Specifies an integer value indicating the desired width of the entry window, in average-size characters of the widget’s font.指定一个整数值,以小部件字体的平均大小字符表示输入窗口的所需宽度。

Virtual events虚拟事件

The combobox widgets generates a <<ComboboxSelected>> virtual event when the user selects an element from the list of values.当用户从值列表中选择一个元素时,组合框小部件生成一个<<ComboboxSelected>>虚拟事件。

ttk.Combobox

classtkinter.ttk.Combobox
current(newindex=None)

If newindex is specified, sets the combobox value to the element position newindex. 如果指定了newindex,则将组合框值设置为元素位置newindexOtherwise, returns the index of the current value or -1 if the current value is not in the values list.否则,返回当前值的索引,如果当前值不在值列表中,则返回-1。

get()

Returns the current value of the combobox.返回组合框的当前值。

set(value)

Sets the value of the combobox to value.将组合框的值设置为value

Spinbox

The ttk.Spinbox widget is a ttk.Entry enhanced with increment and decrement arrows. ttk.Spinbox小部件是一个通过递增和递减箭头增强的ttk.EntryIt can be used for numbers or lists of string values. 它可以用于数字或字符串值列表。This widget is a subclass of Entry.这个小部件是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.除了继承自Widget的方法(Widget.cget()Widget.configure()Widget.identify()Widget.instate()Widget.state())以及继承自Entry的方法(Entry.bbox()Entry.delete()Entry.icursor()Entry.index()Entry.insert()Entry.xview())之外,它还有一些其它方法,在ttk.Spinbox中描述。

Options选项

This widget accepts the following specific options:此小部件接受以下特定选项:

Options选项

Description描述

from

Float value. 浮点值。If set, this is the minimum value to which the decrement button will decrement. 如果设置,这是递减按钮将递减的最小值。Must be spelled as from_ when used as an argument, since from is a Python keyword.用作参数时必须拼写为from_,因为from是Python关键字。

to

Float value. 浮点值。If set, this is the maximum value to which the increment button will increment.如果设置,这是递增按钮将递增的最大值。

increment

Float value. 浮点值。Specifies the amount which the increment/decrement buttons change the value. 指定递增/递减按钮更改值的量。Defaults to 1.0.默认为1.0。

values

Sequence of string or float values. 字符串或浮点值的序列。If specified, the increment/decrement buttons will cycle through the items in this sequence rather than incrementing or decrementing numbers.如果指定,递增/递减按钮将按此顺序循环浏览项目,而不是递增或递减数字。

wrap

Boolean value. 布尔值。If True, increment and decrement buttons will cycle from the to value to the from value or the from value to the to value, respectively.如果为真,递增和递减按钮将分别从to值循环到from值或从from循环到to的值。

format

String value. 字符串值。This specifies the format of numbers set by the increment/decrement buttons. 这指定由递增/递减按钮设置的数字格式。It must be in the form “%W.Pf”, where W is the padded width of the value, P is the precision, and ‘%’ and ‘f’ are literal.它的格式必须为“%W.Pf”,其中W是值的填充宽度,P是精度,“%”和“f”是文字。

command

Python callable. Python是可调用的。Will be called with no arguments whenever either of the increment or decrement buttons are pressed.无论何时按下递增或递减按钮,都将在不带参数的情况下调用。

Virtual events虚拟事件

The spinbox widget generates an <<Increment>> virtual event when the user presses <Up>, and a <<Decrement>> virtual event when the user presses <Down>.当用户按下<Up>时,spinbox小部件生成一个<<Increment>>虚拟事件,当用户按下<Down>时,它生成一个<<Decrement>>虚拟事件。

ttk.Spinbox

classtkinter.ttk.Spinbox
get()

Returns the current value of the spinbox.返回spinbox的当前值。

set(value)

Sets the value of the spinbox to value.将微调框的值设置为value

Notebook

Ttk Notebook widget manages a collection of windows and displays a single one at a time. Ttk笔记本小部件管理一组窗口,并一次显示一个窗口。Each child window is associated with a tab, which the user may select to change the currently-displayed window.每个子窗口与选项卡相关联,用户可以选择该选项卡来改变当前显示的窗口。

Options选项

This widget accepts the following specific options:此小部件接受以下特定选项:

Options选项

Description描述

height

If present and greater than zero, specifies the desired height of the pane area (not including internal padding or tabs). 如果存在且大于零,则指定窗格区域的所需高度(不包括内部填充或选项卡)。Otherwise, the maximum height of all panes is used.否则,将使用所有窗格的最大高度。

padding

Specifies the amount of extra space to add around the outside of the notebook. 指定要在笔记本外部添加的额外空间量。The padding is a list up to four length specifications left top right bottom. 填充是一个列表,最多有四种长度规格:左上右下。If fewer than four elements are specified, bottom defaults to top, right defaults to left, and top defaults to left.如果指定的元素少于四个,则底部默认为顶部,右侧默认为左侧,顶部默认为左侧。

width

If present and greater than zero, specified the desired width of the pane area (not including internal padding). 如果存在且大于零,则指定窗格区域的所需宽度(不包括内部填充)。Otherwise, the maximum width of all panes is used.否则,将使用所有窗格的最大宽度。

Tab Options选项卡选项

There are also specific options for tabs:还有选项卡的特定选项:

Options选项

Description描述

state

Either “normal”, “disabled” or “hidden”. “正常”、“禁用”或“隐藏”。If “disabled”, then the tab is not selectable. 如果“禁用”,则该选项卡不可选择。If “hidden”, then the tab is not shown.如果“隐藏”,则不显示选项卡。

sticky

Specifies how the child window is positioned within the pane area. 指定子窗口在窗格区域中的位置。Value is a string containing zero or more of the characters “n”, “s”, “e” or “w”. 值是包含零个或多个字符“n”、“s”、“e”或“w”的字符串。Each letter refers to a side (north, south, east or west) that the child window will stick to, as per the grid() geometry manager.根据grid()几何体管理器,每个字母都表示子窗口将附着的一侧(北、南、东或西)。

padding

Specifies the amount of extra space to add between the notebook and this pane. 指定要在笔记本和此窗格之间添加的额外空间量。Syntax is the same as for the option padding used by this widget.语法与此小部件使用的选项填充相同。

text

Specifies a text to be displayed in the tab.指定要在选项卡中显示的文本。

image

Specifies an image to display in the tab. 指定要在选项卡中显示的图像。See the option image described in Widget.请参见Widget中描述的选项图像。

compound

Specifies how to display the image relative to the text, in the case both options text and image are present. 指定在同时存在文本和图像选项的情况下,如何相对于文本显示图像。See Label Options for legal values.有关合法值,请参阅标签选项

underline

Specifies the index (0-based) of a character to underline in the text string. 指定要在文本字符串中加下划线的字符的索引(基于0)。The underlined character is used for mnemonic activation if Notebook.enable_traversal() is called.如果调用Notebook.enable_traversal(),带下划线的字符用于助记符激活。

Tab Identifiers标签标识符

The tab_id present in several methods of ttk.Notebook may take any of the following forms:ttk.Notebook的几种方法中的tab_id可以采用以下任何形式:

  • 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形式“@x,y”的位置规范,用于标识选项卡

  • The literal string “current”, which identifies the currently-selected tab文字字符串“current”,用于标识当前选定的选项卡

  • The literal string “end”, which returns the number of tabs (only valid for Notebook.index())文字字符串“end”,返回制表符的数量(仅对Notebook.index()有效)

Virtual Events虚拟事件

This widget generates a <<NotebookTabChanged>> virtual event after a new tab is selected.选择新选项卡后,此小部件将生成一个<<NotebookTabChanged>>虚拟事件。

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 is restored 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 the associated window.删除由tab_id指定的选项卡,取消映射和取消管理关联窗口。

hide(tab_id)

Hides the tab specified by tab_id.隐藏由tab_id指定的选项卡。

The tab will not be displayed, but the associated window remains managed by the notebook and its configuration remembered. 该选项卡将不显示,但相关窗口仍由笔记本管理,并记住其配置。Hidden tabs may be restored with the add() command.可以使用add()命令恢复隐藏的选项卡。

identify(x, y)

Returns the name of the tab element at position x, y, or the empty string if none.返回xy位置的制表符元素的名称,如果没有,则返回空字符串。

index(tab_id)

Returns the numeric index of the tab specified by tab_id, or the total number of tabs if tab_id is the string “end”.返回由tab_id指定的选项卡的数字索引,如果tab_id是字符串“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 a managed child. 是字符串“end”、整数索引或托管子级的名称。If child is already managed by the notebook, moves it to the specified position.如果child已由笔记本管理,则将其移动到指定位置。

See Tab Options for the list of available options.有关可用选项的列表,请参阅选项卡选项

select(tab_id=None)

Selects the specified tab_id.选择指定的tab_id

The associated child window will be displayed, and the previously-selected window (if different) is unmapped. 将显示关联的子窗口,并取消映射先前选择的窗口(如果不同)。If tab_id is omitted, returns the widget name of the currently selected pane.如果省略了tab_id,则返回当前选定窗格的小部件名称。

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

Query or modify the options of the specific tab_id.查询或修改特定tab_id的选项。

If kw is not given, returns a dictionary of the tab option values. 如果未给出kw,则返回选项卡选项值的字典。If option is specified, returns the value of that option. 如果指定了option,则返回该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 the notebook 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, will select that tab.:其中K是任何选项卡的助记符(带下划线),将选择该选项卡。

Multiple notebooks in a single toplevel may be enabled for traversal, including nested notebooks. 可以启用单个顶层中的多个笔记本进行遍历,包括嵌套笔记本。However, notebook traversal only works properly if all panes have the notebook they are in as master.但是,只有当所有窗格都有作为主窗格的笔记本时,笔记本遍历才能正常工作。

Progressbar

The ttk.Progressbar widget shows the status of a long-running operation. ttk.Progressbar小部件显示长期运行操作的状态。It can operate in two modes: 1) the determinate mode which shows the amount completed relative to the total amount of work to be done and 2) the indeterminate mode which provides an animated display to let the user know that work is progressing.它可以在两种模式下运行:1)确定模式,显示相对于待完成工作量的已完成量;2)不确定模式,提供动画显示,让用户知道工作正在进行。

Options选项

This widget accepts the following specific options:此小部件接受以下特定选项:

Options选项

Description描述

orient

One of “horizontal” or “vertical”. “水平”或“垂直”之一。Specifies the orientation of the progress bar.指定进度条的方向。

length

Specifies the length of the long axis of the progress bar (width if horizontal, height if vertical).指定进度条长轴的长度(水平时为宽度,垂直时为高度)。

mode

One of “determinate” or “indeterminate”.“确定”或“不确定”之一。

maximum

A number specifying the maximum value. 指定最大值的数字。Defaults to 100.默认为100。

value

The current value of the progress bar. 进度条的当前值。In “determinate” mode, this represents the amount of work completed. 在“确定”模式下,这表示完成的工作量。In “indeterminate” mode, it is interpreted as modulo maximum; that is, the progress bar completes one “cycle” when its value increases by maximum.在“不确定”模式下,它被解释为模maximum;也就是说,当进度条的值增加到maximum时,进度条完成一个“循环”。

variable

A name which is linked to the option value. 链接到选项值的名称。If specified, the value of the progress bar is automatically set to the value of this name whenever the latter is modified.如果指定,每当修改此名称时,进度条的值将自动设置为该名称的值。

phase

Read-only option. 只读选项。The widget periodically increments the value of this option whenever its value is greater than 0 and, in determinate mode, less than maximum. 每当此选项的值大于0且在确定模式下小于最大值时,小部件会定期递增该选项的值。This option may be used by 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 calls Progressbar.step() every interval milliseconds. 开始自动增量模式:计划一个周期性定时器事件,该事件每隔interval毫秒调用Progressbar.step()If omitted, interval defaults to 50 milliseconds.如果interval省略,interval默认为50毫秒。

step(amount=None)

Increments the progress bar’s value by amount.amount递增进度条的值。

amount defaults to 1.0 if omitted.如果省略amount,则amount默认为1.0。

stop()

Stop autoincrement mode: cancels any recurring timer event initiated by Progressbar.start() for this progress bar.停止自动增量模式:取消由Progressbar.start()为此进度条启动的任何定期计时器事件。

Separator

The ttk.Separator widget displays a horizontal or vertical separator bar.ttk.Separator小部件显示水平或垂直分隔条。

It has no other methods besides the ones inherited from ttk.Widget.除了从ttk.Widget继承的方法之外,它没有其他方法。

Options选项

This widget accepts the following specific option:此小部件接受以下特定选项:

Options选项

Description描述

orient

One of “horizontal” or “vertical”. “水平”或“垂直”之一。Specifies the orientation of the separator.指定分隔符的方向。

Sizegrip

The ttk.Sizegrip widget (also known as a grow box) allows the user to resize the containing toplevel window by pressing and dragging the grip.ttk.Sizegrip小部件(也称为增长框)允许用户通过按住并拖动夹点来调整包含顶层窗口的大小。

This widget has neither specific options nor specific methods, besides the ones inherited from ttk.Widget.除了从ttk.Widget继承的选项之外,这个小部件既没有特定的选项,也没有特定的方法。

Platform-specific notes平台特定注释

  • On macOS, toplevel windows automatically include a built-in size grip by default. 在macOS上,顶级窗口默认情况下自动包含内置大小夹点。Adding a Sizegrip is harmless, since the built-in grip will just mask the widget.添加一个Sizegrip是无害的,因为内置的grip只会屏蔽小部件。

Bugs

  • If the containing toplevel’s position was specified relative to the right or bottom of the screen (e.g. ….), the Sizegrip widget will not resize the window.如果指定了包含顶层的位置相对于屏幕的右侧或底部(例如…),则Sizegrip小部件将不会调整窗口大小。

  • This widget supports only “southeast” resizing.此小部件仅支持“东南”调整大小。

Treeview

The ttk.Treeview widget displays a hierarchical collection of items. ttk.Treeview小部件显示项目的分层集合。Each item has a textual label, an optional image, and an optional list of data values. 每个项都有一个文本标签、一个可选图像和一个可选数据值列表。The data values are displayed in successive columns after the tree label.数据值显示在树标签后的连续列中。

The order in which data values are displayed may be controlled by setting the widget option displaycolumns. 可以通过设置小部件选项displaycolumns来控制数据值的显示顺序。The tree widget can also display column headings. 树小部件还可以显示列标题。Columns may be accessed by number or symbolic names listed in the widget option columns. 可以通过小部件选项列中列出的数字或符号名称访问列。See Column Identifiers.请参见列标识符

Each item is identified by a unique name. 每个项目都由一个唯一的名称标识。The widget will generate item IDs if they are not supplied by the caller. 如果调用者没有提供项目ID,小部件将生成项目ID。There is a distinguished root item, named {}. 有一个名为{}的可分辨根项。The root item itself is not displayed; its children appear at the top level of the hierarchy.不显示根项目本身;其子级显示在层次结构的顶层。

Each item also has a list of tags, which can be used to associate event bindings with individual items and control the appearance of the item.每个项还具有一个标记列表,可用于将事件绑定与单个项关联,并控制项的外观。

The Treeview widget supports horizontal and vertical scrolling, according to the options described in Scrollable Widget Options and the methods Treeview.xview() and Treeview.yview().Treeview小部件支持水平和垂直滚动,这取决于可滚动小部件选项中描述的选项以及Treeview.xview()方法和Treeview.yview()方法。

Options选项

This widget accepts the following specific options:此小部件接受以下特定选项:

Options选项

Description描述

columns

A list of column identifiers, specifying the number of columns and their names.列标识符列表,指定列数及其名称。

displaycolumns

A list of column identifiers (either symbolic or integer indices) specifying which data columns are displayed and the order in which they appear, or the string “#all”.列标识符列表(符号或整数索引),指定显示哪些数据列及其显示顺序,或字符串“#all”。

height

Specifies the number of rows which should be visible. Note: the requested width is determined from the sum of the column widths.指定应可见的行数。注意:请求的宽度由列宽之和确定。

padding

Specifies the internal padding for the widget. 指定小部件的内部填充。The padding is a list of up to four length specifications.填充是最多四种长度规格的列表。

selectmode

Controls how the built-in class bindings manage the selection. 控制内置类绑定如何管理选择。One of “extended”, “browse” or “none”. “扩展”、“浏览”或“无”之一。If set to “extended” (the default), multiple items may be selected. 如果设置为“扩展”(默认),则可以选择多个项目。If “browse”, only a single item will be selected at a time. 如果“浏览”,一次只选择一个项目。If “none”, the selection will not be changed.如果为“无”,则不会更改选择。

Note that the application code and tag bindings can set the selection however they wish, regardless of the value of this option.请注意,应用程序代码和标记绑定可以任意设置选择,而不管此选项的值如何。

show

A list containing zero or more of the following values, specifying which elements of the tree to display.包含以下零个或多个值的列表,指定要显示的树元素。

  • tree: display tree labels in column #0.树:在列#0中显示树标签。

  • headings: display the heading row.标题:显示标题行。

The default is “tree headings”, i.e., show all elements.默认为“树标题”,即显示所有元素。

Note: Column #0 always refers to the tree column, even if show=”tree” is not specified.:列#0始终引用树列,即使未指定show=“tree”。

Item Options选项

The following item options may be specified for items in the insert and item widget commands.可以为插入和项目小部件命令中的项目指定以下项目选项。

Options选项

Description描述

text

The textual label to display for the item.要为项目显示的文本标签。

image

A Tk Image, displayed to the left of the label.标签左侧显示的Tk图像。

values

The list of values associated with the item.与项目关联的值列表。

Each item should have the same number of values as the widget option columns. 每个项应具有与小部件选项列相同数量的值。If there are fewer values than columns, the remaining values are assumed empty. 如果值少于列,则其余值假定为空。If there are more values than columns, the extra values are ignored.如果值多于列,则忽略额外的值。

open

True/False value indicating whether the item’s children should be displayed or hidden.值,该值指示应显示还是隐藏项的子项。

tags

A list of tags associated with this item.与此项目关联的标记列表。

Tag Options选项

The following options may be specified on tags:可以在标签上指定以下选项:

Options选项

Description描述

foreground

Specifies the text foreground color.指定文本的前景色。

background

Specifies the cell or item background color.指定单元格或项目背景颜色。

font

Specifies the font to use when drawing text.指定绘制文本时使用的字体。

image

Specifies the item image, in case the item’s image option is empty.如果项目的图像选项为空,则指定项目图像。

Column Identifiers列标识符

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.整数n,指定第n个数据列。

  • A string of the form #n, where n is an integer, specifying the nth display column.形式为#n的字符串,其中n是整数,指定第n个显示列。

Notes:

  • Item’s option values may be displayed in a different order than the order in which they are stored.项目选项值的显示顺序可能与存储顺序不同。

  • Column #0 always refers to the tree column, even if show=”tree” is not specified.列#0始终引用树列,即使未指定show=“tree”。

A data column number is an index into an item’s option values list; a display column number is the column number in the tree where the values are displayed. 数据列编号是项目选项值列表的索引;显示列编号是树中显示值的列编号。Tree labels are displayed in column #0. 树标签显示在列#0中。If option displaycolumns is not set, then data column n is displayed in column #n+1. 如果未设置选项displaycolumns,则数据列n显示在列#n+1中。Again, column #0 always refers to the tree column.同样,列#0总是指树列

Virtual Events虚拟事件

The Treeview widget generates the following virtual events.Treeview小部件生成以下虚拟事件。

Event事件

Description描述

<<TreeviewSelect>>

Generated whenever the selection changes.每当选择更改时生成。

<<TreeviewOpen>>

Generated just before settings the focus item to open=True.在将焦点项设置为open=True之前生成。

<<TreeviewClose>>

Generated just after setting the focus item to open=False.将焦点项设置为open=False后立即生成。

The Treeview.focus() and Treeview.selection() methods can be used to determine the affected item or items.Treeview.focus()Treeview.selection()方法可用于确定受影响的项。

ttk.Treeview

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

Returns the bounding box (relative to the treeview widget’s window) of the specified item in the form (x, y, width, height).返回以(x, y, width, height)形式指定item的边界框(相对于treeview小部件的窗口)。

If column is specified, returns the bounding box of that cell. 如果指定了column,则返回该单元格的边界框。If the item is not visible (i.e., if it is a descendant of a closed item or is scrolled offscreen), returns an empty string.如果该item不可见(即,如果它是已关闭项的子项或滚动到屏幕外),则返回空字符串。

get_children(item=None)

Returns the list of children belonging to item.返回属于item的子项列表。

If item is not specified, returns root children.如果未指定item,则返回根子项。

set_children(item, *newchildren)

Replaces item’s child with newchildren.newchildren替换item的子项。

Children present in item that are not present in newchildren are detached from the tree. 存在于item中但不存在于newchildren中的子项将从树中分离。No items in newchildren may be an ancestor of item. newchildren中的项不能是item的祖先。Note that not specifying newchildren results in detaching item’s children.注意,不指定newchildren会导致分离item的子项。

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

Query or modify the options for the specified column.查询或修改指定column的选项。

If kw is not given, returns a dict of the column option values. 如果未给出kw,则返回列选项值的dict。If option is specified then the value for that option is returned. 如果指定了option,则返回该option的值。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.:标准Tk锚定值之一。

    Specifies how the text in this column should be aligned with respect to the cell.指定此列中的文本应如何与单元格对齐。

  • minwidth: width

    The minimum width of the column in pixels. 列的最小宽度(以像素为单位)。The treeview widget will not make the column any smaller than specified by this option when the widget is resized or the user drags a column.当调整小部件的大小或用户拖动列时,treeview小部件不会使列小于此选项指定的值。

  • stretch: True/False

    Specifies whether the column’s width should be adjusted when the widget is resized.指定在调整小部件的大小时是否应调整列的宽度。

  • width: width

    The width of the column in pixels.列的宽度(以像素为单位)。

To configure the tree column, call this with column = “#0”要配置树列,请使用column=“#0”调用

delete(*items)

Delete all specified items and all their descendants.删除所有指定items及其所有子项。

The root item may not be deleted.不能删除根项目。

detach(*items)

Unlinks all of the specified items from the tree.取消树中所有指定items的链接。

The items and all of their descendants are still present, and may be reinserted at another point in the tree, but will not be displayed.这些项及其所有子项仍然存在,可以在树中的其他点重新插入,但不会显示。

The root item may not be detached.无法分离根项目。

exists(item)

Returns True if the specified item is present in the tree.如果树中存在指定item,则返回True

focus(item=None)

If item is specified, sets the focus item to item. 如果指定了item,则将焦点项设置为itemOtherwise, returns the current focus item, or ‘’ if there is none.否则,返回当前焦点项,如果没有,则返回“”。

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

Query or modify the heading options for the specified column.查询或修改指定column的标题选项。

If kw is not given, returns a dict of the heading option values. 如果未给出kw,则返回航向选项值的dict。If option is specified then the value for that option is returned. 如果指定了option,则返回该option的值。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 standard Tk anchor values.标准Tk锚定值之一。

  • command: callback

    A callback to be invoked when the heading label is pressed.按下标题标签时要调用的回调。

To configure the tree column heading, call this with column = “#0”.要配置树列标题,请使用column=“#0”调用此选项。

identify(component, x, y)

Returns a description of the specified component under the point given by x and y, or the empty string if no such component is present at that position.返回xy给定点下指定component的描述,如果该位置不存在此类component,则返回空字符串。

identify_row(y)

Returns the item ID of the item at position y.返回位置y处项目的项目ID。

identify_column(x)

Returns the data column identifier of the cell at position x.返回位置x处单元格的数据列标识符。

The tree column has ID #0.树列的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.可用性:Tk 8.6。

identify_element(x, y)

Returns the element at position x, y.返回xy位置的元素。

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 created item.创建新项并返回新创建项的项标识符。

parent is the item ID of the parent item, or the empty string to create a new top-level item. 父项的项ID,或用于创建新顶级项的空字符串。index is an integer, or the value “end”, specifying where in the list of parent’s children to insert the new item. 是一个整数,或值“end”,指定在父项的子项列表中插入新项的位置。If index is less than or equal to zero, the new node is inserted at the beginning; if index is greater than or equal to the current number of children, it is inserted at the end. 如果index小于或等于零,则在开始处插入新节点;如果index大于或等于当前子级数,则在末尾插入。If iid is specified, it is used as the item identifier; iid must not already exist in the tree. 如果指定了iid,则将其用作项目标识符;树中不能已经存在iidOtherwise, 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.查询或修改指定item的选项。

If no options are given, a dict with options/values for the item is returned. 如果未给出选项,则返回包含该项的选项/值的dict。If option is specified then the value for that option is returned. 如果指定了option,则返回该选项的值。Otherwise, sets the options to the corresponding values as given by kw.否则,将选项设置为kw给定的相应值。

move(item, parent, index)

Moves item to position index in parent’s list of children.item移动到父项parent的子项列表中的位置index

It is illegal to move an item under one of its descendants. 将项移动到其子项下是非法的。If index is less than or equal to zero, item is moved to the beginning; if greater than or equal to the number of children, it is moved to the end. 如果index小于或等于零,则item移动到开头;如果大于或等于子项的数量,则将其移动到末尾。If item was detached it is reattached.如果item已分离,则会重新连接。

next(item)

Returns the identifier of item’s next sibling, or ‘’ if item is the last child of its parent.返回item的下一个同级的标识符,如果item是其父项的最后一个子项,则返回“”。

parent(item)

Returns the ID of the parent of item, or ‘’ if item is at the top level of the hierarchy.返回item的父项的ID,如果item位于层次结构的顶层,则返回“”。

prev(item)

Returns the identifier of item’s previous sibling, or ‘’ if item is the first child of its parent.返回item的前一个同级的标识符,如果item是其父项的第一个子项,则返回“”。

reattach(item, parent, index)

An alias for Treeview.move().Treeview.move()的别名。

see(item)

Ensure that item is visible.确保item可见。

Sets all of item’s ancestors open option to True, and scrolls the widget if necessary so that item is within the visible portion of the tree.item的所有祖先打开选项设置为True,并在必要时滚动小部件,以便item位于树的可见部分内。

selection()

Returns a tuple of selected items.返回选定项的元组。

Changed in version 3.8:版本3.8中更改: selection() no longer takes arguments. 它不再需要争论。For changing the selection state use the following selection methods.要更改选择状态,请使用以下选择方法。

selection_set(*items)

items becomes the new selection.成为新的选区。

Changed in version 3.6:版本3.6中更改: items can be passed as separate arguments, not just as a single tuple.可以作为单独的参数传递,而不仅仅是作为单个元组传递。

selection_add(*items)

Add items to the selection.items添加到选区。

Changed in version 3.6:版本3.6中更改: items can be passed as separate arguments, not just as a single tuple.可以作为单独的参数传递,而不仅仅是作为单个元组传递。

selection_remove(*items)

Remove items from the selection.从选区中删除items

Changed in version 3.6:版本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.切换items中每个项目的选择状态。

Changed in version 3.6:版本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 the specified item. 使用一个参数,返回指定item的列/值对字典。With two arguments, returns the current value of the specified column. 使用两个参数,返回指定column的当前值。With three arguments, sets the value of given column in given item to the specified value.使用三个参数,将给定item中给定column的值设置为指定value

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

Bind a callback for the given event sequence to the tag tagname. 将给定事件sequence的回调绑定到标记tagnameWhen an event is delivered to an item, the callbacks for each of the item’s tags option are called.当一个事件传递到一个项目时,将调用该项目的每个标记选项的回调。

tag_configure(tagname, option=None, **kw)

Query or modify the options for the specified tagname.查询或修改指定tagname的选项。

If kw is not given, returns a dict of the option settings for tagname. 如果未给出kw,则返回tagname选项设置的dict。If option is specified, returns the value for that option for the specified tagname. 如果指定了option,则返回指定tagname的该option的值。Otherwise, sets the options to the corresponding values for the given tagname.否则,将选项设置为给定tagname的相应值。

tag_has(tagname, item=None)

If item is specified, returns 1 or 0 depending on whether the specified item has the given tagname. 如果指定了item,则根据指定item是否具有给定tagname,返回1或0。Otherwise, returns a list of all items that 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 of elements making up the widget and how they are arranged, along with dynamic and default settings for element options. ttk中的每个小部件都分配了一个样式,该样式指定了组成小部件的元素集及其排列方式,以及元素选项的动态和默认设置。By default the style name is the same as the widget’s class name, but it may be overridden by the widget’s style option. 默认情况下,样式名与小部件的类名相同,但可能会被小部件的样式选项覆盖。If you don’t know the class name of a widget, use the method Misc.winfo_class() (somewidget.winfo_class()).如果您不知道小部件的类名,请使用方法Misc.winfo_class()somewidget.winfo_class())。

See also参阅

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) in style.style中查询或设置指定选项的默认值。

Each key in kw is an option and each value is a string identifying the value for that option.kw中的每个键都是一个选项,每个值都是标识该选项值的字符串。

For example, to change every default button to be a flat button with some padding and a different background color:例如,要将每个默认按钮更改为带有一些填充和不同背景颜色的平面按钮,请执行以下操作:

from tkinter import ttk
import tkinter
root = 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) in style.style中查询或设置指定选项的动态值。

Each key in kw is an option and each value should be a list or a tuple (usually) containing statespecs grouped in tuples, lists, or some other preference. kw中的每个键都是一个选项,每个值都应该是一个列表或一个元组(通常),其中包含以元组、列表或其他首选项分组的状态规范。A statespec is a compound of one or more states and then a value.statespec是一个或多个状态和一个值的组合。

An example may make it more understandable:举个例子可能会让它更容易理解:

import tkinter
from tkinter import ttk
root = 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 does matter, if the order is changed to [('active', 'blue'), ('pressed', 'red')] in the foreground option, for example, the result would be a blue foreground when the widget were in active or pressed states.请注意,选项的(状态,值)序列的顺序并不重要,例如,如果在前景选项中将顺序更改为[('active', 'blue'), ('pressed', 'red')],则当小部件处于活动或按下状态时,结果将是蓝色前景。

lookup(style, option, state=None, default=None)

Returns the value specified for option in style.返回为style中的option指定的值。

If state is specified, it is expected to be a sequence of one or more states. 如果指定了state,则它应该是一个或多个状态的序列。If the default argument is set, it is used as a fallback value in case no specification for option is found.如果设置了default参数,则在找不到选项规范的情况下,它将用作回退值。

To check what font a Button uses by default:要检查按钮默认使用的字体,请执行以下操作:

from tkinter import ttk
print(ttk.Style().lookup("TButton", "font"))
layout(style, layoutspec=None)

Define the widget layout for given style. 定义给定style的小部件布局。If layoutspec is omitted, return the layout specification for given style.如果省略layoutspec,则返回给定style的布局规范。

layoutspec, if specified, is expected to be a list or some other sequence type (excluding strings), where each item should be a tuple and the first item is the layout name and the second item should have the format described in Layouts.layoutspec(如果指定)应为列表或其他序列类型(不包括字符串),其中每个项应为元组,第一项为布局名称,第二项应具有布局中描述的格式。

To understand the format, see the following example (it is not intended to do anything useful):要了解格式,请参阅以下示例(它不打算做任何有用的事情):

from tkinter import ttk
import tkinter
root = 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 given etype which is expected to be either “image”, “from” or “vsapi”. 在当前主题中创建给定etype的新元素,该元素应为“image”、“from”或“vsapi”。The latter is only available in Tk 8.6a for Windows XP and Vista and is not described here.后者仅在适用于Windows XP和Vista的Tk 8.6a中可用,此处不作说明。

If “image” is used, args should contain the default image name followed by statespec/value pairs (this is the imagespec), and kw may have the following options:如果使用“image”,则args应包含默认图像名称,后跟statespec/值对(这是imagespec),kw可能具有以下选项:

  • border=padding

    padding is a list of up to four integers, specifying the left, top, right, and bottom borders, respectively.padding是一个最多四个整数的列表,分别指定左、上、右和下边框。

  • height=height

    Specifies a minimum height for the element. 指定图元的最小高度。If less than zero, the base image’s height is used as a default.如果小于零,则使用基础图像的高度作为默认值。

  • padding=padding

    Specifies the element’s interior padding. 指定元素的内部填充。Defaults to border’s value if not specified.如果未指定,则默认为边框的值。

  • sticky=spec

    Specifies how the image is placed within the final parcel. 指定如何将图像放置在最终地块中。spec contains zero or more characters “n”, “s”, “w”, or “e”.规范包含零个或多个字符“n”、“s”、“w”或“e”。

  • width=width

    Specifies a minimum width for the element. 指定元素的最小宽度。If less than zero, the base image’s width is used as a default.如果小于零,则使用基础图像的宽度作为默认值。

If “from” is used as the value of etype, element_create() will clone an existing element. 如果使用“from”作为etype的值,element_create()将克隆现有元素。args is expected to contain a themename, from which the element will be cloned, and optionally an element to clone from. 预期包含一个主题名,将从中克隆元素,并可选地包含一个要从中克隆的元素。If this element to clone from is not specified, an empty element will be used. 如果未指定要从中克隆的元素,则将使用空元素。kw is discarded.被丢弃。

element_names()

Returns the list of elements defined in the current theme.返回当前主题中定义的元素列表。

element_options(elementname)

Returns the list of elementname’s options.返回elementname的选项列表。

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

Create a new theme.创建一个新主题。

It is an error if themename already exists. 如果themename已存在,则为错误。If parent is specified, the new theme will inherit styles, elements and layouts from the parent theme. 如果指定了parent,则新主题将从父主题继承样式、元素和布局。If settings are present they are expected to have the same syntax used for theme_settings().如果存在settings,则它们应具有用于theme_settings()的相同语法。

theme_settings(themename, settings)

Temporarily sets the current theme to themename, apply specified settings and then restore the previous theme.将当前主题临时设置为themename,应用指定的settings,然后还原以前的主题。

Each key in settings is a style and each value may contain the keys ‘configure’, ‘map’, ‘layout’ and ‘element create’ and they are expected to have the same format as specified by the methods Style.configure(), Style.map(), Style.layout() and Style.element_create() respectively.settings中的每个键都是一种样式,每个值都可能包含键“配置”、“映射”、“布局”和“元素创建”,它们的格式应与分别由方法Style.configure()Style.map()Style.layout()Style.element_create()指定的格式相同。

As an example, let’s change the Combobox for the default theme a bit:例如,让我们稍微更改一下默认主题的组合框:

from tkinter import ttk
import tkinter
root = 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()

Returns a list of all known themes.返回所有已知主题的列表。

theme_use(themename=None)

If themename is not given, returns the theme in use. 如果未给出themename,则返回正在使用的主题。Otherwise, sets the current theme to themename, refreshes all widgets and emits a <<ThemeChanged>> event.否则,将当前主题设置为themename,刷新所有小部件并发出 <<ThemeChanged>>事件。

Layouts布局

A layout can be just None, if it takes no options, or a dict of options specifying how to arrange the element. 布局可以是None,如果它不需要选项,也可以是指定如何排列元素的一组选项。The layout mechanism uses a simplified version of the pack geometry manager: given an initial cavity, each element is allocated a parcel. 布局机制使用包几何图形管理器的简化版本:给定初始空腔,每个图元将分配一个地块。Valid options/values are:有效选项/值为:

  • side: whichside

    Specifies which side of the cavity to place the element; one of top, right, bottom or left. 指定要放置图元的腔的哪一侧;顶部、右侧、底部或左侧之一。If omitted, the element occupies the entire cavity.如果省略,则该元件占据整个空腔。

  • 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 as a single element for the purposes of Widget.identify() et al. 如果设置为1,将导致该元素及其所有子元素被视为单个元素,以便Widget.identify()等。It’s used for things like scrollbar thumbs with grips.它用于滚动条拇指和夹点之类的东西。

  • children: [sublayout… ]

    Specifies a list of elements to place inside the element. 指定要放置在元素内的元素列表。Each element is a tuple (or other sequence type) where the first item is the layout name, and the other is a Layout.每个元素都是元组(或其他序列类型),其中第一项是布局名称,另一项是布局