tkinter.ttk --- Tk のテーマ付きウィジェット

ソースコード: Lib/tkinter/ttk.py


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

The basic idea for tkinter.ttk is to separate, to the extent possible, the code implementing a widget's behavior from the code implementing its appearance.

Added in version 3.1.

参考

Tk Widget Styling Support

Tk のテーマサポートを紹介するドキュメント

Ttk を使う

Ttk を使い始めるために、モジュールをインポートします:

from tkinter import ttk

基本的な 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.

This has the direct benefit of using the new widgets which gives a better look and feel across platforms; however, the replacement widgets are not completely compatible. The main difference is that widget options such as "fg", "bg" and others related to widget styling are no longer present in Ttk widgets. Instead, use the ttk.Style class for improved styling effects.

参考

Converting existing applications to use Tile widgets

アプリケーションを移行して新しいウィジェットを使用する際に出くわす典型的な差異について (Tcl の用語を使って) 書かれている研究論文

Ttk widgets

Ttk には 18 のウィジェットがあり、そのうち 12 は Tkinter に既にあるものです: Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale, Scrollbar, Spinbox 。新しい 6 つは次のものです: Combobox, Notebook, Progressbar, Separator, Sizegrip, Treeview 。そして、これらは全て Widget の子クラスです。

Ttk ウィジェットを使用すると、アプリケーションの見た目と使いやすさが向上します。上述の通り、書式をコーディングする方法は異なります。

Tk のコード

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

Ttk のコード:

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")

TtkStyling についての詳細は Style クラスの文書を読んでください。

ウィジェット

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

Standard options

All the ttk Widgets accept the following options:

オプション

説明

クラス

ウィンドウクラスを指定します。このクラスはオプションデータベースにウィンドウの他のオプションについて問い合わせを行うときに使われ、これによりウィンドウのデフォルトのバインドタグを決定したり、ウィジェットのデフォルトのレイアウトやスタイルを選択します。このオプションは読み出し専用で、ウィンドウが作成されるときにのみ指定できます。

cursor

Specifies the mouse cursor to be used for the widget. If set to the empty string (the default), the cursor is inherited from the parent widget.

takefocus

キーボードによる移動のときにウィンドウがフォーカスを受け入れるかを決定します。0、1、空文字列のいずれかを返します。0 が返されると、キーボードによる移動でそのウィンドウは常にスキップされます。1 なら、そのウィンドウが表示されているときに限り入力フォーカスを受け入れます。そして空文字列は、移動スクリプトによってウィンドウにフォーカスを当てるかどうかが決まることを意味します。

style

独自のウィジェットスタイルを指定するのに使われます。

Scrollable widget options

以下のオプションはスクロールバーで操作されるウィジェットが持っているオプションです。

オプション

説明

xscrollcommand

水平方向のスクロールバーとのやり取りに使われます。

When the view in the widget's window changes, the widget calls the xscrollcommand callback.

Usually this option consists of the method Scrollbar.set of some scrollbar. This will cause the scrollbar to be updated whenever the view in the window changes.

yscrollcommand

垂直方向のスクロールバーとのやり取りに使われます。詳しくは、上記を参照してください。

Label options

以下のオプションはラベルやボタンやボタンに類似したウィジェットが持っているオプションです。

オプション

説明

text

ウィジェットに表示される文字列を指定します。

textvariable

text オプションの代わりに使う値の変数名を指定します。

underline

このオプションを設定すると、文字列の中で下線を引く文字のインデックス (0 基点) を指定します。下線が引かれた文字はショートカットとして使われます。

image

表示する画像を指定します。これは 1 つ以上の要素を持つリストです。先頭の要素はデフォルトの画像名です。残りの要素は Style.map() で定義されているような状態名と値のペアの並びで、ウィジェットがある状態、もしくはある状態の組み合わせにいるときに使用する別の画像を指定します。このリストにある全ての画像は同じサイズでなればなりません。

compound

text オプションと image オプションが両方とも指定されていた場合に、テキストに対して画像をどう配置するかを指定します。適当な値は:

  • text: テキストのみ表示する

  • image: 画像のみ表示する

  • top, bottom, left, right: それぞれ画像をテキストの上、下、左、右に配置する。

  • none: デフォルト。もしあれば画像を表示し、そうでなければテキストを表示する。

0 より大きい場合、テキストラベルを作成するのにどれくらいのスペースを使うかを文字の幅で指定します。0 より小さい場合、最小の幅が指定されます。0 もしくは無指定の場合、テキストラベルに対して自然な幅が使われます。

Compatibility options

オプション

説明

state

"normal" か "disabled" に設定され、 "disabled" 状態のビットをコントロールします。これは書き込み専用のオプションです: これを設定するとウィジェットの状態を変更できますが、 Widget.state() メソッドはこのオプションに影響を及ぼしません。

Widget states

ウィジェットの状態は独立した状態フラグのビットマップです。

Flag

説明

active

マウスカーソルがウィジェットの上にあり、マウスのボタンをクリックすることで何らかの動作をさせられます

disabled

プログラムによってウィジェットは無効化されています

focus

ウィジェットにキーボードフォーカスがあります

pressed

ウィジェットは押されています

selected

チェックボタンやラジオボタンのようなウィジェットでの "オン" や "チェック有" や "選択中" に当たります

background

Windows と Mac には "アクティブな" もしくは最前面のウィンドウという概念があります。背面のウィンドウにあるウィジェットには background 状態が設定され、最前面のウィンドウにあるウィジェットでは解除されます

readonly

ウィジェットはユーザからの変更を受け付けません

alternate

ウィジェット特有の切り替え表示になっています

invalid

ウィジェットの値が不正です

状態仕様は状態名の並びになっていて、状態名の先頭にはビットがオフになっていることを示す感嘆符が付くことがあります。

ttk.Widget

Besides the methods described below, the ttk.Widget supports the methods tkinter.Widget.cget and tkinter.Widget.configure.

class tkinter.ttk.Widget
identify(x, y)

x y の位置にある要素の名前、もしくはその位置に要素が無ければ空文字列を返します。

xy はウィジェットに対するピクセル単位の座標です。

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

ウィジェットの状態をチェックします。コールバックが指定されていない場合、ウィジェットの状態が statespec に一致していれば True 、そうでなければ False を返します。コールバックが指定されていて、ウィジェットの状態が statespec に一致している場合、引数に args を指定してそのコールバックを呼び出します。

state(statespec=None)

ウィジェットの状態を変更したり、取得したりします。statespec が指定されている場合、それに応じてウィジェットの状態を設定し、どのフラグが変更されたかを示す新しい statespec を返します。statespec が指定されていない場合、現在の状態フラグを返します。

Not to be confused with Wm.state.

通常 statespec はリストもしくはタプルです。

コンボボックス

The ttk.Combobox widget combines a text field with a pop-down list of values. This widget is a subclass of Entry.

Besides the methods inherited from Widget: cget(), configure(), identify(), instate() and state(), and the following inherited from Entry: bbox(), delete(), icursor(), index(), insert(), selection*, xview*, it has some other methods, described at ttk.Combobox.

オプション

このウィジェットは以下の固有のオプションを受け付けます:

オプション

説明

exportselection

Boolean value. If set, the widget selection is linked to the X selection (which can be returned by invoking Misc.selection_get, for example).

justify

ウィジェットの中でテキストをどう配置するかを指定します。 "left", "center", "right" のうちのどれか 1 つです。

高さ

ポップダウンリストの高さを行数で指定します。

postcommand

コンボボックスの値を表示する直前に呼び出される、(Misc.register などで登録した) スクリプトです。どの値を表示するかについても指定できます。

state

One of "normal", "readonly", or "disabled". In the "readonly" state, the value may not be edited directly, and the user can only select one 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

コンボボックスの値とリンクさせる変数名を指定します。その変数の値が変更されたとき、ウィジェットの値は更新されます。ウィジェットの値が更新されたときも同様です。 tkinter.StringVar を参照してください。

values

ドロップダウンリストに表示する値のリストを指定します。

入力ウィンドウに必要な幅をウィジェットのフォントの平均的なサイズの文字で測った、文字数を指定します。

注釈

Tk 9.1 added the locale option, which selects the locale used to determine word and character boundaries within the text ("C" by default).

仮想イベント

コンボボックスウィジェットは、ユーザが値のリストから1つ選んだときに仮想イベント <<ComboboxSelected>> を生成します。

ttk.Combobox

class tkinter.ttk.Combobox
current(newindex=None)

newindex が指定されている場合、コンボボックスの値がドロップダウンリストの newindex の位置にある値に設定されます。そうでない場合、現在の値のインデックスを、もしくは現在の値がリストに含まれていないなら -1 を返します。

get()

コンボボックスの現在の値を返します。

set(value)

コンボボックスの値を value に設定します。

Spinbox

The ttk.Spinbox widget is a ttk.Entry enhanced with increment and decrement arrows. It can be used for numbers or lists of string values. This widget is a subclass of Entry. Besides the methods inherited from Widget: cget(), configure(), identify(), instate() and state(), and the following inherited from Entry: bbox(), delete(), icursor(), index(), insert(), xview*, it has some other methods, described at ttk.Spinbox.

オプション

このウィジェットは以下の固有のオプションを受け付けます:

オプション

説明

from

Float value. If set, this is the minimum value to which the decrement button will decrement. Must be spelled as from_ when used as an argument, since from is a Python keyword.

to

Float value. If set, this is the maximum value to which the increment button will increment.

increment

Float value. Specifies the amount which the increment/decrement buttons change the value. Defaults to 1.0.

values

Sequence of string or float values. If specified, the increment/decrement buttons will cycle through the items in this sequence rather than incrementing or decrementing numbers.

wrap

Boolean value. If True, increment and decrement buttons will cycle from the to value to the from value or the from value to the to value, respectively.

format

String value. This specifies the format of numbers set by the increment/decrement buttons. It must be in the form "%W.Pf", where W is the padded width of the value, P is the precision, and '%' and 'f' are literal.

command

Python callable. Will be called with no arguments whenever either of the increment or decrement buttons are pressed.

仮想イベント

The spinbox widget generates an <<Increment>> virtual event when the user presses <Up>, and a <<Decrement>> virtual event when the user presses <Down>.

ttk.Spinbox

class tkinter.ttk.Spinbox

Added in version 3.8.

get()

Returns the current value of the spinbox.

set(value)

Sets the value of the spinbox to value.

ノートブック

ノートブックウィジェットは複数のウィンドウを管理し、同時に 1 つのウィンドウを表示します。それぞれの子ウィンドウはタブの関連付けられていて、ユーザはそれを選択して表示されているウィンドウを切り替えます。

オプション

このウィジェットは以下の固有のオプションを受け付けます:

オプション

説明

高さ

0 より大きな値が設定されている場合、 (内部のパディングやタブを含まない) ペイン領域に必要な高さを指定します。設定されていない場合、全てのペインの高さの最大値が使われます。

padding

ノートブックの外周に付け足す追加の領域の量を指定します。パディングは最大 4 個の長さ指定のリストです: 左、上、右、下の順で指定します。4 個より少ない場合、デフォルトで下は上と、右は左と、上は左と同じ値が、それぞれ使われます。

0 より大きな値が指定されている場合、(内部のパディングを含まない) ペイン領域に必要な幅を指定します。設定されていない場合、全てのペインの幅の最大値が使われます。

Tab options

タブ用のオプションもあります:

オプション

説明

state

"normal", "disabled", "hidden" のうちどれか 1 つです。 "disabled" の場合、タブは選択することができません。 "hidden" の場合、タブは表示されません。

sticky

Specifies how the child window is positioned within the pane area. Value is a string containing zero or more of the characters "n", "s", "e" or "w". Each letter refers to a side (north, south, east or west) that the child window will stick to, as per the grid geometry manager.

padding

ノートブックとこのペインの間に付け足す追加の領域の量を指定します。文法はこのウィジェットの padding オプションと同じです。

text

タブに表示するテキストを指定します。

image

タブに表示する画像を指定します。 Widget のオプション image の説明を参照してください。

compound

text オプションと image オプションが両方指定されているときにテキストに対して画像をどう表示するかを指定します。指定する値については Label Options を参照してください。

underline

テキスト中の下線を引く文字のインデックス (0 基点) を指定します。 Notebook.enable_traversal() が呼ばれていた場合、下線が引かれた文字はショートカットとして使われます。

Tab identifiers

The tab_id present in several methods of ttk.Notebook may take any of the following forms:

  • 0 からタブの数の間の整数

  • 子ウィンドウの名前

  • タブを指し示す "@x,y" という形式の位置指定

  • 現在選択されているタブを指し示すリテラル文字列 "current"

  • タブ数を返すリテラル文字列 "end" (Notebook.index() でのみ有効)

仮想イベント

このウィジェットは新しいタブが選択された後に仮想イベント <<NotebookTabChanged>> を生成します。

ttk.Notebook

class tkinter.ttk.Notebook
add(child, **kw)

ノートブックに新しいタブを追加します。

ウィンドウが現在ノートブックによって管理されているが隠れている場合、以前の位置に復元します。

利用可能なオプションのリストについては Tab Options を参照してください。

forget(tab_id)

tab_id で指定されたタブを削除します。関連付けられていたウィンドウは切り離され、管理対象でなくなります。

This shadows the inherited geometry-manager forget(); use pack_forget(), grid_forget() or place_forget() to remove the widget itself from its manager.

hide(tab_id)

tab_id で指定されたタブを隠します。

タブは表示されませんが、関連付いているウィンドウはノートブックによって保持されていて、その設定も記憶されています。隠れたタブは add() コマンドで復元できます。

identify(x, y)

x y の位置にあるタブの名前を、そこにタブが無ければ空文字列を返します。

index(tab_id)

tab_id で指定されたタブのインデックスを、 tab_id が文字列の "end" だった場合はタブの総数を返します。

insert(pos, child, **kw)

指定された位置にペインを挿入します。

pos は文字列の "end" か整数のインデックスか管理されている子ウィンドウの名前です。 child が既にノートブックの管理対象だった場合、指定された場所に移動させます。

利用可能なオプションのリストについては Tab Options を参照してください。

select(tab_id=None)

指定された tab_id を選択します。

関連付いている子ウィンドウは表示され、直前に選択されていたウィンドウは (もし異なれば) 表示されなくなります。 tab_id が指定されていない場合は、現在選択されているペインのウィジェット名を返します。

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

指定された tab_id のオプションを問い合わせたり、変更したりします。

kw が与えられなかった場合、タブのオプション値の辞書を返します。 option が指定されていた場合、その option の値を返します。それ以外の場合は、オプションに対応する値が設定されます。

tabs()

Returns a tuple of windows managed by the notebook.

enable_traversal()

このノートブックを含む最上位にあるウィンドウでのキーボード移動を可能にします。

これによりノートブックを含んだ最上位にあるウィンドウに対し、以下のキーバインディングが追加されます:

  • Control-Tab: 現在選択されているタブの 1 つ次のタブを選択します。

  • Shift-Control-Tab: 現在選択されているタブの 1 つ前のタブを選択します。

  • Alt-K: K があるタブの (下線が引かれた) ショートカットキーだとして、そのタブを選択します。

Multiple notebooks in a single toplevel may be enabled for traversal, including nested notebooks. However, notebook traversal only works properly if all panes are direct children of the notebook.

プログレスバー

The ttk.Progressbar widget shows the status of a long-running operation. It can operate in two modes: 1) the determinate mode which shows the amount completed relative to the total amount of work to be done and 2) the indeterminate mode which provides an animated display to let the user know that work is progressing.

オプション

このウィジェットは以下の固有のオプションを受け付けます:

オプション

説明

orient

"horizontal" もしくは "vertical" のいずれかです。プログレスバーの方向を指定します。

length

プログレスバーの長さを指定します。 (水平方向の場合は幅、垂直方向の場合は高さです)

mode

"determinate" か "indeterminate" のいずれかです。

maximum

最大値を数値で指定します。デフォルトは 100 です。

value

プログレスバーの現在値です。決定的 ("determinate") モードでは、完了した処理の量を表します。非決定的 ("indeterminate") モードでは、 maximum を法として解釈され、値が maximum に達したときにプログレスバーは 1 "サイクル" を完了したことになります。

variable

value オプションとリンクさせる変数名です。指定されている場合、変数の値が変更されるとプログレスバーの値は自動的にその値に設定されます。

phase

読み出し専用のオプションです。このウィジェットの値が 0 より大きく、かつ決定的モードでは最大値より小さいときに、ウィジェットが定期的にこのオプションの値を増加させます。このオプションは現在の画面テーマが追加のアニメーション効果を出すのに使います。

ttk.Progressbar

class tkinter.ttk.Progressbar
start(interval=None)

自動増加モードを開始します: interval ミリ秒ごとに Progressbar.step() を繰り返し呼び出すタイマーイベントを設定します。引数で指定しない場合は、 interval はデフォルトで 50 ミリ秒になります。

step(amount=None)

プログレスバーの値を amount だけ増加させます。

引数で指定しない場合は、 amount はデフォルトで 1.0 になります。

stop()

自動増加モードを停止します: このプログレスバーの Progressbar.start() で開始された繰り返しのタイマーイベントを全てキャンセルします。

セパレータ

The ttk.Separator widget displays a horizontal or vertical separator bar.

It has no other methods besides the ones inherited from ttk.Widget.

オプション

このウィジェットは次の特定のオプションを受け付けます。

オプション

説明

orient

"horizontal" か "vertical" のいずれかです。セパレータの方向を指定します。

サイズグリップ

The ttk.Sizegrip widget (also known as a grow box) allows the user to resize the containing toplevel window by pressing and dragging the grip.

This widget has neither specific options nor specific methods, besides the ones inherited from ttk.Widget.

プラットフォーム固有のメモ

  • macOS では、最上位のウィンドウにはデフォルトで組み込みのサイズグリップが含まれています。組み込みのグリップが Sizegrip を隠してしまうので、 Sizegrip を追加しても問題ありません。

バグ

  • If the containing toplevel's position was specified relative to the right or bottom of the screen (for example, ....), the Sizegrip widget will not resize the window.

  • このウィジェットは "南東" 方向のサイズ変更しかサポートしていません。

ツリービュー

The ttk.Treeview widget displays a hierarchical collection of items. Each item has a textual label, an optional image, and an optional list of data values. The data values are displayed in successive columns after the tree label.

データが表示される順序はウィジェットの displaycolumns オプションで制御されます。ツリーウィジェットはカラムヘッダを表示することもできます。カラムには数字もしくはウィジェットの columns オプションにある名前でアクセスできます。 Column Identifiers を参照してください。

それぞれの要素は一意な名前で識別されます。要素の作成時に識別子が与えられなかった場合、ウィジェットが要素の識別子を生成します。このウィジェットには {} という名前の特別なルート要素があります。ルート要素自身は表示されません; その子要素たちが階層の最上位に現れます。

それぞれの要素はタグのリストも持っていて、イベントバインディングと個別の要素を関連付け、要素の見た目を管理するのに使えます。

ツリービューウィジェットは水平方向と垂直方向のスクロールをサポートしていて、 Scrollable Widget Options に記述してあるオプションと Treeview.xview() メソッドおよび Treeview.yview() メソッドが使えます。

オプション

このウィジェットは以下の固有のオプションを受け付けます:

オプション

説明

columns

カラム数とその名前を指定するカラム識別子のリストです。

displaycolumns

どのデータカラムをどの順序で表示するかを指定する、 (名前もしくは整数のインデックスの) カラム識別子のリストか、文字列 "#all" です。

高さ

表示する行数を指定します。メモ: 表示に必要な幅はカラム幅の合計から決定されます。

padding

ウィジェットの内部のパディングのサイズを指定します。パディングは最大 4 個の長さ指定のリストです。

selectmode

組み込みのクラスバインディングが選択状態をどう管理するかを指定します。設定する値は "extended", "browse", "none" のどれか 1 つです。 "extended" に設定した場合 (デフォルト)、複数の要素が選択できます。 "browse" に設定した場合、同時に 1 つの要素しか選択できません。 "none" に設定した場合、選択を変更することはできません。

このオプションの値によらず、アプリケーションのコードと関連付けられているタグからは好きなように選択状態を設定できます。

show

ツリーのどの要素を表示するかを指定する、以下にある値を 0 個以上含むリストです。

  • tree: カラム #0 にツリーのラベルを表示します。

  • headings: ヘッダ行を表示します。

The default is "tree headings", that is, show all elements.

メモ: show="tree" が指定されていない場合でも、カラム #0 は常にツリーカラムを参照します。

注釈

Tk 9.0 added several Treeview features. The selectmode option gained the values "single" and "multiple"; the new widget options selecttype ("item" or "cell" selection), striped (zebra-striped rows), and titlecolumns / titleitems (columns or rows frozen against scrolling) were introduced; and items gained a hidden option. Tk 9.1 added the rowheight and headingheight options.

Item options

以下の要素オプションは、ウィジェットの insert コマンドと item コマンドで要素に対して指定できます。

オプション

説明

text

アイテムに表示するテキストラベルです。

image

ラベルの左に表示される Tk 画像です。

values

要素に関連付けられている値のリストです。

それぞれの要素はウィジェットの columns オプションと同じ数の値を持たなければいけません。 columns オプションより少ない場合、残りの値は空として扱われます。 columns オプションより多い場合、余計な値は無視されます。

open

要素の子供を表示するか隠すかを指示する True/False 値です。

tags

この要素に関連付いているタグのリストです。

Tag options

以下のオプションはタグに対して設定できます:

オプション

説明

foreground

テキストの色を指定します。

background

セルや要素の背景色を指定します。

font

テキストを描画するときに使うフォントを指定します。

image

要素の image オプションが空だった場合に使用する画像を指定します。

Column identifiers

カラム識別子は以下のいずれかの形式を取ります:

  • columns オプションのリストにある名前。

  • n 番目のデータカラムを指し示す整数 n 。

  • n を整数として n 番目の表示されているカラムを指し示す #n という形式の文字列。

注釈:

  • 要素のオプション値は実際に格納されている順序とは違った順序で表示されることがあります。

  • show="tree" が指定されていない場合でも、カラム #0 は常にツリーカラムを指しています。

データカラムを指す数字は、要素の values オプションのリストのインデックスです; 表示カラムを指す数字は、値が表示されているツリーのカラム番号です。ツリーラベルはカラム #0 に表示されます。 displaycolumns オプションが設定されていない場合は、 n 番目のデータカラムはカラム #n+1 に表示されます。再度言っておくと、 カラム #0 は常にツリーカラムを指します

仮想イベント

ツリービューは以下の仮想イベントを生成します。

Event

説明

<<TreeviewSelect>>

選択状態が変更されたときに生成されます。

<<TreeviewOpen>>

フォーカスが当たっている要素に open=True が設定される直前に生成されます。

<<TreeviewClose>>

フォーカスが当たっている要素に open=False が設定された直後に生成されます。

Treeview.focus() メソッドと Treeview.selection() メソッドは変更を受けた要素を判別するのに使えます。

ttk.Treeview

class tkinter.ttk.Treeview
bbox(item, column=None)

(ツリービューウィジェットのウィンドウを基準として) 指定された item のバウンディングボックス情報を (x 座標, y 座標, 幅, 高さ) の形式で返します。

If column is specified, returns the bounding box of that cell. If the item is not visible (that is, if it is a descendant of a closed item or is scrolled offscreen), returns an empty string.

This shadows the inherited Misc.bbox(); use grid_bbox() for the grid bounding box.

get_children(item=None)

Returns a tuple of children belonging to item.

item が指定されていなかった場合は、ルート要素の子供が返されます。

set_children(item, *newchildren)

Replaces item's children with newchildren.

item にいる子供のうち newchildren にないものはツリーから切り離されます。 newchildren にあるどの要素も item の祖先であってはいけません。 newchildren を指定しなかった場合は、 item の子要素が全て切り離されることに注意してください。

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

指定した column のオプションを問い合わせたり、変更したりします。

kw が与えられなかった場合は、カラムのオプション値の辞書が返されます。 option が指定されていた場合は、その option の値が返されます。それ以外の場合は、オプションに値を設定します。

設定できるオプションとその値は次の通りです:

id

カラム名を返します。これは読み出し専用のオプションです。

anchor: One of the standard Tk anchor values.

このカラムでセルに対してテキストをどう配置するかを指定します。

minwidth: width

カラムの最小幅をピクセル単位で表したものです。ツリービューウィジェットは、ウィジェットのサイズが変更されたりカラムをユーザがドラッグして移動させたりしたときに、このオプションで指定した幅より狭くすることはありません。

stretch: True/False

ウィジェットがサイズ変更されたとき、カラムの幅をそれに合わせるかどうかを指定します。

width: width

カラムの幅をピクセル単位で表したものです。

ツリーカラムの設定を行うには、 column = "#0" を付けてこのメソッドを呼び出してください。

delete(*items)

指定された items とその子孫たち全てを削除します。

ルート要素は削除されません。

detach(*items)

指定された items を全てツリーから切り離します。

その要素と子孫たちは依然として存在していて、ツリーの別の場所に再度挿入することができますが、隠された状態になり表示はされません。

ルート要素は切り離されません。

exists(item)

Returns True if the specified item is present in the tree, False otherwise.

focus(item=None)

item が指定されていた場合は、 item にフォーカスを当てます。そうでない場合は、現在フォーカスが当たっている要素が、どの要素にもフォーカスが当たっていない場合は '' が返されます。

This shadows the inherited Misc.focus(); use focus_set() to focus the widget itself.

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

指定された column の heading のオプションを問い合わせたり、変更したりします。

kw が与えられなかった場合は、見出しのオプション値の辞書が返されます。 option が指定されている場合は、 option の値が返されます。それ以外の場合は、オプションに値を設定します。

設定できるオプションとその値は次の通りです:

text: text

カラムの見出しに表示するテキスト。

image: imageName

カラムの見出しの右に表示する画像を指定します。

anchor: anchor

見出しのテキストをどう配置するかを指定します。標準の Tk anchor の値です。

command: callback

見出しラベルがクリックされたときに実行されるコールバックです。

ツリーカラムの見出しの設定を行うには、 column = "#0" を付けてこのメソッドを呼び出してください。

identify(component, x, y)

x y で与えられた場所にある指定された component の説明を返します。その場所に指定された component が無い場合は空文字列を返します。 (訳注: component には "region", "item", "column", "row", "element" が指定でき、それぞれ "cell", "heading" などの場所の名前、要素の識別子、 #n という形式のカラム名、その行にある要素の識別子、 "text", "padding" などの画面構成要素の名前を返します。)

identify_row(y)

y 座標が y の位置にある要素の識別子を返します。

identify_column(x)

Returns the display column identifier of the cell at position x.

ツリーカラムは #0 という識別子を持ちます。

identify_region(x, y)

以下のうち 1 つを返します:

region

意味

heading

ツリーの見出し領域

separator

2 つのカラム見出しの間のスペース

tree

ツリーの領域

cell

データセル

使用可能バージョン: Tk 8.6

identify_element(x, y)

x y の位置にある画面構成要素の名前を返します。

使用可能バージョン: Tk 8.6

index(item)

親要素の子要素リストの中での item のインデックスを返します。

insert(parent, index, iid=None, **kw)

新しい要素を作り、その要素の識別子を返します。

parent は親となる要素の識別子で、空文字列にすると新しい要素を最上位に作成します。 index は整数もしくは "end" という値で、それによって親要素の子要素リストのどこに新しい要素を挿入するかを指定します。 index が 0 以下だった場合は、新しい要素は先頭に挿入されます; index が現在の子要素の数以上だった場合は末尾に挿入されます。 iid が指定された場合は、要素の識別子として使われます; iid はまだツリーに存在していないものに限ります。それ以外の場合は、一意な識別子が生成されます。

See Item Options for the list of available options.

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

指定された item のオプションを問い合わせたり、変更したりします。

オプションが与えられなかった場合は、要素のオプションと値が辞書の形で返されます。 option が指定された場合は、そのオプションの値が返されます。それ以外の場合は、 kw で与えられたようにオプションに値が設定されます。

move(item, parent, index)

itemparent の子要素リストの index の位置に移動します。

要素を自身の子孫の下に移動させるのは許されていません。 index が 0 以下の場合、 item は先頭に移動されます; 子要素の数以上だった場合、末尾に移動されます。 item が切り離された状態の場合は、再度取り付けられます。

reattach() is an alias of move().

next(item)

item の 1 つ下の兄弟の識別子を、 item が親にとって一番下の子供だった場合 '' を返します。

parent(item)

item の親の識別子を、 item が階層の最上位にいた場合 '' を返します。

prev(item)

item の 1 つ上の兄弟の識別子を、 item が親にとって一番上の子供だった場合 '' を返します。

see(item)

item を見える状態にします。

item の全ての子孫の open オプションを True にし、必要であれば item がツリーの見える範囲に来るようにウィジェットをスクロールさせます。

selection()

Returns a tuple of selected items.

バージョン 3.8 で変更: selection() no longer takes arguments. For changing the selection state use the following selection methods.

selection_set(*items)

新しく選択状態の要素が items になります。

バージョン 3.6 で変更: items は 1 つのタプルとしてだけでなく、別々の引数としても渡せます。

selection_add(*items)

選択状態の要素として items を追加します。

バージョン 3.6 で変更: items は 1 つのタプルとしてだけでなく、別々の引数としても渡せます。

selection_remove(*items)

選択状態の要素から items を取り除きます。

バージョン 3.6 で変更: items は 1 つのタプルとしてだけでなく、別々の引数としても渡せます。

selection_toggle(*items)

items のそれぞれの要素の選択状態を入れ替えます。

バージョン 3.6 で変更: items は 1 つのタプルとしてだけでなく、別々の引数としても渡せます。

set(item, column=None, value=None)

1 引数で呼び出された場合、指定された item のカラムと値のペアからなる辞書を返します。 2 引数で呼び出された場合、指定された column の現在の値を返します。 3 引数で呼び出された場合、与えられた itemcolumn を指定された値 value に設定します。

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

与えられたイベント sequence 用のコールバックをタグ tagname にバインドします。イベントが要素に渡ってきたときに、要素の tags オプションのそれぞれのコールバックが呼び出されます。

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

指定された tagname のオプションを問い合わせたり、変更したりします。

kw が与えられなかった場合、 tagname のオプション設定を辞書の形で返します。 option が指定された場合、指定された tagnameoption の値を返します。それ以外の場合、与えられた tagname のオプションに値を設定します。

tag_has(tagname, item=None)

If item is specified, returns True if the specified item has the given tagname and False otherwise. Otherwise, returns a tuple of all items that have the specified tag.

使用可能バージョン: Tk 8.6

xview(*args)

ツリービューの水平方向の位置を問い合わせたり、変更したりします。

yview(*args)

ツリービューの垂直方向の位置を問い合わせたり、変更したりします。

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

参考

Tcl'2004 conference のプレゼンテーション

この文書ではテーマエンジンがどう動くかを説明しています

class tkinter.ttk.Style

このクラスはスタイルデータベースを操作するために使われます。

configure(style, query_opt=None, **kw)

style の指定されたオプションのデフォルト値を問い合わせたり、設定したりします。

kw のそれぞれのキーはオプション名で値はそのオプションの値の文字列です。

例えば、全てのデフォルトのボタンをパディングのある平らな見た目にし、背景の色を変更するには以下のようにします:

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)

style の指定されたオプションの動的な値を問い合わせたり、設定したりします。

kw のそれぞれのキーはオプション名で、値はタプルやリストや何か他のお好みのものでグループ化された状態仕様 (statespec) を要素とするリストやタプルです。状態仕様は 1 つもしくは複数の状態と値の組み合わせです。

以下のように、例を示す方がわかりやすいでしょう:

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()

あるオプションに対する状態と値の組 (states, value) の並び順はスタイルに影響を与えることに注意してください。例えば、foreground オプションの順序を [('active', 'blue'), ('pressed', 'red')] に変更した場合、ウィジェットがアクティブもしくは押された状態のとき前面が青くなります。

When called to query the map (without specifying values to set), it returns a dictionary mapping each option to its list of statespecs.

バージョン 3.10 で変更: The value returned when querying the map was corrected.

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

style の指定された option の値を返します。

state を指定する場合は、1 つ以上の状態名の並びである必要があります。 default 引数が指定されていた場合は、オプション指定が見付からなかったときに代わりに返される値として使われます。

デフォルトでボタンがどのフォントを使うかを調べるには、以下のように実行します:

from tkinter import ttk

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

与えられた style でのウィジェットのレイアウトを定義します。 layoutspec が省略されていた場合は、与えられたスタイルのレイアウト仕様を返します。

layoutspec を指定する場合は、リストもしくは (文字列を除いた) 何か他のシーケンス型である必要があります。それぞれの要素はタプルで、レイアウト名を 1 番目の要素とし、2 番目の要素は Layouts で説明されているフォーマットである必要があります。

フォーマットを理解するために以下の例を見てください (何かを使い易くするための例ではありません):

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". The latter is only available in Tk 8.6 on Windows.

"image" が使われた場合、 args はデフォルトの画像名の後ろに状態仕様と値のペア (これが画像仕様です) を並べたものである必要があります。 kw には以下のオプションが指定できます:

border=padding

padding は 4 個以下の整数のリストで、それぞれ左、上、右、下の縁の幅を指定します。

height=height

要素の最小の高さを指定します。0 より小さい場合は、画像の高さをデフォルトとして使用します。

padding=padding

要素の内部のパディングを指定します。指定されない場合は、 border の値がデフォルトとして使われます。

sticky=spec

1 つ外側の枠に対し画像をどう配置するかを指定します。 spec は "n", "s", "w", "e" の文字を 0 個以上含みます。

width=width

要素の最小の幅を指定します。0 より小さい場合は、画像の幅をデフォルトとして使用します。

以下はプログラム例です:

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')

etype の値として "from" が使われた場合は、 element_create() が現在の要素を複製します。 args は要素の複製元のテーマの名前と、オプションで複製する要素を含んでいる必要があります。複製元の要素が指定されていなかった場合、空要素が使用され、 kw は破棄されます。

以下はプログラム例です:

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

If "vsapi" is used as the value of etype, element_create() will create a new element in the current theme whose visual appearance is drawn using the Microsoft Visual Styles API which is responsible for the themed styles on Windows XP and Vista. args is expected to contain the Visual Styles class and part as given in the Microsoft documentation followed by an optional sequence of tuples of ttk states and the corresponding Visual Styles API state value. 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 horizontal and the vertical padding; a single number specifies the same padding 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 queried for the recommended size or the part. If this option is set then height should also be set. The width and height options cannot be mixed with the padding or margins options.

height=height

Specifies the height of the element. See the comments for width.

以下はプログラム例です:

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 a tuple of elements defined in the current theme.

element_options(elementname)

Returns a tuple of elementname's options.

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

新しいテーマを作成します。

themename が既に存在していた場合はエラーになります。 parent が指定されていた場合は、新しいテーマは親テーマからスタイルや要素やレイアウトを継承します。 settings が指定された場合は、 theme_settings() で使われるのと同じ形式である必要があります。

theme_settings(themename, settings)

一時的に現在のテーマを themename に設定し、指定された settings を適用した後、元のテーマを復元します。

settings のそれぞれのキーはスタイル名で値はさらに 'configure', 'map', 'layout', 'element create' をキーとして持ち、その値はそれぞれ Style.configure(), Style.map(), Style.layout(), Style.element_create() メソッドで指定するのと同じ形式である必要があります。

例として、コンボボックスの default テーマを少し変更してみましょう

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 tuple of all known themes.

theme_use(themename=None)

themename が与えられなかった場合は、現在使用中のテーマ名を返します。そうでない場合は、現在のテーマを themename に設定し、全てのウィジェットを再描画し、 <<ThemeChanged>> イベントを発生させます。

レイアウト

A layout can be just None, if it takes no options, or a dict of options specifying how to arrange the element. The layout mechanism uses a simplified version of the pack geometry manager: given an initial cavity, each element is allocated a parcel.

設定できるオプションとその値は次の通りです:

side: whichside

要素を空間のどちら側に配置するかを指定します; top, right, bottom, left のどれか 1 つです。省略された場合は、要素は空間全体を占めます。

sticky: nswe

配分された空間の内部に要素をどう配置するかを指定します。

unit: 0 or 1

1 に設定されると、 Widget.identify() などには要素とその子で単一の要素として扱われます。これは、グリップのついたスクロールバーサムのようなものに使われます。

children: [sublayout... ]

要素の内部に配置する要素のリストを指定します。リストのそれぞれの要素はタプル (もしくは他のシーケンス型) で、それの 1 番目の要素はレイアウト名でそれ以降は Layout です。

Additional widgets

The following themed widgets complete the tkinter.ttk widget set. Each is the themed counterpart of the like-named classic tkinter widget and inherits the common methods of Widget.

class tkinter.ttk.Button(master=None, **kw)

Ttk Button widget, displays a textual label and/or image, and evaluates a command when pressed. It is the themed counterpart of tkinter.Button and inherits the common widget methods from Widget.

invoke()

Invoke the command associated with the button and return its result.

class tkinter.ttk.Checkbutton(master=None, **kw)

Ttk Checkbutton widget, used to control a boolean variable that is toggled on and off. It is the themed counterpart of tkinter.Checkbutton and inherits the common widget methods from Widget.

invoke()

Toggle the button between its selected and deselected states, invoke the command associated with the button, and return its result.

class tkinter.ttk.Entry(master=None, widget=None, **kw)

Ttk Entry widget, displays a one-line text string and allows the user to edit it. It is the themed counterpart of tkinter.Entry and inherits the common widget methods from Widget as well as the editing methods from tkinter.Entry.

bbox(index)

Return a tuple (x, y, width, height) giving the bounding box of the character at the given index.

This shadows the inherited Misc.bbox(); use grid_bbox() for the grid bounding box.

identify(x, y)

Return the name of the element under the point given by x and y, or the empty string if no element is present at that location.

validate()

Force validation of the entry and return True if validation succeeded, and False otherwise.

class tkinter.ttk.Frame(master=None, **kw)

Ttk Frame widget, a container used to group and lay out other widgets. It is the themed counterpart of tkinter.Frame and inherits the common widget methods from Widget.

class tkinter.ttk.Label(master=None, **kw)

Ttk Label widget, displays a textual label and/or image. It is the themed counterpart of tkinter.Label and inherits the common widget methods from Widget.

class tkinter.ttk.Labelframe(master=None, **kw)

Ttk Labelframe widget, a container that draws a border and a title label around its contents. It is the themed counterpart of tkinter.LabelFrame and inherits the common widget methods from Widget.

class tkinter.ttk.Menubutton(master=None, **kw)

Ttk Menubutton widget, displays a textual label and/or image, and pops up a menu when pressed. It is the themed counterpart of tkinter.Menubutton and inherits the common widget methods from Widget.

class tkinter.ttk.OptionMenu(master, variable, default=None, *values, **kwargs)

Ttk OptionMenu widget, a Menubutton that pops up a menu of mutually exclusive choices. variable is the variable that tracks the currently selected value, default is the value to set initially, and values are the entries to display in the menu. A command keyword argument may be given to specify a callable that is invoked with the selected value whenever the selection changes; the style keyword argument sets the style used by the underlying menubutton; and the name keyword argument sets the Tk widget name.

set_menu(default=None, *values)

Replace the entries of the menu with values. If default is given, also set it as the current value of the variable.

destroy()

Destroy this widget and its associated menu.

バージョン 3.14 で変更: Added support for the name keyword argument.

class tkinter.ttk.Panedwindow(master=None, **kw)

Ttk Panedwindow widget, displays a number of subwindows stacked either vertically or horizontally. The user may adjust the relative sizes of the subwindows by dragging the sash between panes. It is the themed counterpart of tkinter.PanedWindow and inherits the common widget methods from Widget, as well as the add() and panes() methods from tkinter.PanedWindow.

insert(pos, child, **kw)

Insert a pane containing child at the position pos. pos is either the string 'end', an integer index, or the name of a managed subwindow. If child is already managed by the paned window, move it to the specified position. Any keyword arguments set pane options.

forget(child)

Remove child, which may be either an integer index or the name of a managed subwindow, from the panes.

This shadows the inherited geometry-manager forget(); use pack_forget(), grid_forget() or place_forget() to remove the widget itself from its manager.

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

Query or modify the options of the specified pane, where pane is either an integer index or the name of a managed subwindow. If no arguments are given, return a dictionary of the pane option values. If option is specified, return the value of that option. Otherwise, set the options given as keyword arguments to their corresponding values.

sashpos(index, newpos=None)

If newpos is specified, set the position of sash number index and return its new position. This may adjust the positions of adjacent sashes to ensure that positions are monotonically increasing; positions are also constrained to be between 0 and the total size of the widget. If newpos is omitted, return the current position of the sash.

class tkinter.ttk.Radiobutton(master=None, **kw)

Ttk Radiobutton widget, used as part of a group to control a single shared variable by selecting one of several mutually exclusive values. It is the themed counterpart of tkinter.Radiobutton and inherits the common widget methods from Widget.

invoke()

Set the option variable to the button's value, select the button, invoke the command associated with the button, and return its result.

class tkinter.ttk.Scale(master=None, **kw)

Ttk Scale widget, displays a slider that lets the user select a numeric value from a range by moving the slider along a trough. It is the themed counterpart of tkinter.Scale and inherits the common widget methods from Widget.

configure(cnf=None, **kw)

Modify or query the widget options, like Widget.configure. In addition, this method clips the from and to values so that the current value stays within the range defined by them.

バージョン 3.9 で変更: Now returns the configuration value, like Widget.configure.

get(x=None, y=None)

Return the current value of the scale. If x and y are given, return the value corresponding to the pixel coordinate x, y instead.

class tkinter.ttk.Scrollbar(master=None, **kw)

Ttk Scrollbar widget, controls the viewport of an associated scrollable widget such as a Treeview, Entry or tkinter.Text. It is the themed counterpart of tkinter.Scrollbar and inherits the common widget methods from Widget, as well as the set() and get() methods from tkinter.Scrollbar.

class tkinter.ttk.Separator(master=None, **kw)

Ttk Separator widget, displays a horizontal or vertical separator line. It has no direct counterpart in tkinter and inherits the common widget methods from Widget.

class tkinter.ttk.Sizegrip(master=None, **kw)

Ttk Sizegrip widget, displays a grip that allows the user to resize the containing toplevel window by pressing and dragging the grip, typically placed in the bottom-right corner. It has no direct counterpart in tkinter and inherits the common widget methods from Widget.

class tkinter.ttk.LabeledScale(master=None, variable=None, from_=0, to=10, **kw)

A Frame containing a Scale and a Label that shows the scale's current value. variable is the IntVar tracked by the scale (one is created if it is not given), and from_ and to define the range of the scale.

destroy()

Destroy this widget and remove the trace callback registered on the associated variable.

class tkinter.ttk.LabelFrame(master=None, **kw)

Alias of Labelframe, kept for naming compatibility with tkinter.LabelFrame.

class tkinter.ttk.PanedWindow(master=None, **kw)

Alias of Panedwindow, kept for naming compatibility with tkinter.PanedWindow.