tkinter —— Tcl/Tk 的 Python 接口?

源代碼: Lib/tkinter/__init__.py


The tkinter package ("Tk interface") is the standard Python interface to the Tcl/Tk GUI toolkit. Both Tk and tkinter are available on most Unix platforms, including macOS, as well as on Windows systems.

若在命令行執(zhí)行 python -m tkinter,應(yīng)會(huì)彈出一個(gè)簡(jiǎn)單的 Tk 界面窗口, 表明 tkinter 包已安裝完成,還會(huì)顯示當(dāng)前安裝的 Tcl/Tk 版本,以便閱讀對(duì)應(yīng)版本的 Tcl/Tk 文檔。

Tkinter 支持眾多的 Tcl/Tk 版本,帶或不帶多線程版本均可。官方的 Python 二進(jìn)制版本捆綁了 Tcl/Tk 8.6 多線程版本。關(guān)于可支持版本的更多信息,請(qǐng)參閱 _tkinter 模塊的源代碼。

Tkinter 并不只是做了簡(jiǎn)單的封裝,而是增加了相當(dāng)多的代碼邏輯,讓使用體驗(yàn)更具 Python 風(fēng)格(pythonic) 。本文將集中介紹這些增加和變化部分,關(guān)于未改動(dòng)部分的細(xì)節(jié),請(qǐng)參考 Tcl/Tk 官方文檔。

備注

Tcl/Tk 8.5 (2007) introduced a modern set of themed user interface components along with a new API to use them. Both old and new APIs are still available. Most documentation you will find online still uses the old API and can be woefully outdated.

參見

  • TkDocs

    Extensive tutorial on creating user interfaces with Tkinter. Explains key concepts, and illustrates recommended approaches using the modern API.

  • Tkinter 8.5 參考手冊(cè):一種 Python GUI

    Reference documentation for Tkinter 8.5 detailing available classes, methods, and options.

Tcl/Tk Resources:

  • Tk 命令

    Comprehensive reference to each of the underlying Tcl/Tk commands used by Tkinter.

  • Tcl/Tk Home Page

    Additional documentation, and links to Tcl/Tk core development.

Books:

架構(gòu)?

Tcl/Tk is not a single library but rather consists of a few distinct modules, each with separate functionality and its own official documentation. Python's binary releases also ship an add-on module together with it.

Tcl

Tcl 是一種動(dòng)態(tài)解釋型編程語言,正如 Python 一樣。盡管它可作為一種通用的編程語言單獨(dú)使用,但最常見的用法還是作為腳本引擎或 Tk 工具包的接口嵌入到 C 程序中。Tcl 庫有一個(gè) C 接口,用于創(chuàng)建和管理一個(gè)或多個(gè) Tcl 解釋器實(shí)例,并在這些實(shí)例中運(yùn)行 Tcl 命令和腳本,添加用 Tcl 或 C 語言實(shí)現(xiàn)的自定義命令。每個(gè)解釋器都擁有一個(gè)事件隊(duì)列,某些部件可向解釋器發(fā)送事件交由其處理。與 Python 不同,Tcl 的執(zhí)行模型是圍繞協(xié)同多任務(wù)而設(shè)計(jì)的,Tkinter 協(xié)調(diào)了兩者的差別(詳見 Threading model )。

Tk

Tk 是用 C 語言實(shí)現(xiàn)的 Tcl 包,加入了創(chuàng)建和操作 GUI 部件的自定義命令。每個(gè) Tk 對(duì)象都嵌入了自己的 Tcl 解釋器實(shí)例,并載入 Tk 。Tk 的部件是可高度自定義的,不過代價(jià)是過時(shí)的外觀。Tk 利用 Tcl 的事件隊(duì)列來生成并處理 GUI 事件。

Ttk

帶有主題的 Tk(Ttk)是較新加入的 Tk 部件,相比很多經(jīng)典的 Tk 部件,在各平臺(tái)提供的界面更加美觀。自 Tk 8.5 版本開始,Ttk 作為 Tk 的成員進(jìn)行發(fā)布。Python 則捆綁在一個(gè)單獨(dú)的模塊中, tkinter.ttk。

Internally, Tk and Ttk use facilities of the underlying operating system, i.e., Xlib on Unix/X11, Cocoa on macOS, GDI on Windows.

When your Python application uses a class in Tkinter, e.g., to create a widget, the tkinter module first assembles a Tcl/Tk command string. It passes that Tcl command string to an internal _tkinter binary module, which then calls the Tcl interpreter to evaluate it. The Tcl interpreter will then call into the Tk and/or Ttk packages, which will in turn make calls to Xlib, Cocoa, or GDI.

Tkinter 模塊?

Support for Tkinter is spread across several modules. Most applications will need the main tkinter module, as well as the tkinter.ttk module, which provides the modern themed widget set and API:

from tkinter import *
from tkinter import ttk
class tkinter.Tk(screenName=None, baseName=None, className='Tk', useTk=True, sync=False, use=None)?

Construct a toplevel Tk widget, which is usually the main window of an application, and initialize a Tcl interpreter for this widget. Each instance has its own associated Tcl interpreter.

The Tk class is typically instantiated using all default values. However, the following keyword arguments are currently recognized:

screenName

When given (as a string), sets the DISPLAY environment variable. (X11 only)

baseName

Name of the profile file. By default, baseName is derived from the program name (sys.argv[0]).

className

Name of the widget class. Used as a profile file and also as the name with which Tcl is invoked (argv0 in interp).

useTk

If True, initialize the Tk subsystem. The tkinter.Tcl() function sets this to False.

sync

If True, execute all X server commands synchronously, so that errors are reported immediately. Can be used for debugging. (X11 only)

use

Specifies the id of the window in which to embed the application, instead of it being created as an independent toplevel window. id must be specified in the same way as the value for the -use option for toplevel widgets (that is, it has a form like that returned by winfo_id()).

Note that on some platforms this will only work correctly if id refers to a Tk frame or toplevel that has its -container option enabled.

Tk reads and interprets profile files, named .className.tcl and .baseName.tcl, into the Tcl interpreter and calls exec() on the contents of .className.py and .baseName.py. The path for the profile files is the HOME environment variable or, if that isn't defined, then os.curdir.

tk?

The Tk application object created by instantiating Tk. This provides access to the Tcl interpreter. Each widget that is attached the same instance of Tk has the same value for its tk attribute.

master?

The widget object that contains this widget. For Tk, the master is None because it is the main window. The terms master and parent are similar and sometimes used interchangeably as argument names; however, calling winfo_parent() returns a string of the widget name whereas master returns the object. parent/child reflects the tree-like relationship while master/slave reflects the container structure.

children?

The immediate descendants of this widget as a dict with the child widget names as the keys and the child instance objects as the values.

tkinter.Tcl(screenName=None, baseName=None, className='Tk', useTk=False)?

Tcl() 函數(shù)是一個(gè)工廠函數(shù),它創(chuàng)建的對(duì)象類似于 Tk 類創(chuàng)建的,只是不會(huì)初始化 Tk 子系統(tǒng)。這在調(diào)動(dòng) Tcl 解釋器時(shí)最為有用,這時(shí)不想創(chuàng)建多余的頂層窗口,或者無法創(chuàng)建(比如不帶 X 服務(wù)的 Unix/Linux 系統(tǒng))。由 Tcl() 創(chuàng)建的對(duì)象可調(diào)用 loadtk() 方法創(chuàng)建一個(gè)頂層窗口(且會(huì)初始化 Tk 子系統(tǒng))。

The modules that provide Tk support include:

tkinter

Main Tkinter module.

tkinter.colorchooser

讓用戶選擇顏色的對(duì)話框。

tkinter.commondialog

本文其他模塊定義的對(duì)話框的基類。

tkinter.filedialog

允許用戶指定文件的通用對(duì)話框,用于打開或保存文件。

tkinter.font

幫助操作字體的工具。

tkinter.messagebox

訪問標(biāo)準(zhǔn)的 Tk 對(duì)話框。

tkinter.scrolledtext

內(nèi)置縱向滾動(dòng)條的文本組件。

tkinter.simpledialog

基礎(chǔ)對(duì)話框和一些便捷功能。

tkinter.ttk

Themed widget set introduced in Tk 8.5, providing modern alternatives for many of the classic widgets in the main tkinter module.

Additional modules:

_tkinter

A binary module that contains the low-level interface to Tcl/Tk. It is automatically imported by the main tkinter module, and should never be used directly by application programmers. It is usually a shared library (or DLL), but might in some cases be statically linked with the Python interpreter.

idlelib

Python's Integrated Development and Learning Environment (IDLE). Based on tkinter.

tkinter.constants

Symbolic constants that can be used in place of strings when passing various parameters to Tkinter calls. Automatically imported by the main tkinter module.

tkinter.dnd

(experimental) Drag-and-drop support for tkinter. This will become deprecated when it is replaced with the Tk DND.

tkinter.tix

(deprecated) An older third-party Tcl/Tk package that adds several new widgets. Better alternatives for most can be found in tkinter.ttk.

turtle

Tk 窗口中的海龜繪圖庫。

Tkinter 拾遺?

This section is not designed to be an exhaustive tutorial on either Tk or Tkinter. For that, refer to one of the external resources noted earlier. Instead, this section provides a very quick orientation to what a Tkinter application looks like, identifies foundational Tk concepts, and explains how the Tkinter wrapper is structured.

The remainder of this section will help you to identify the classes, methods, and options you'll need in your Tkinter application, and where to find more detailed documentation on them, including in the official Tcl/Tk reference manual.

A Hello World Program?

We'll start by walking through a "Hello World" application in Tkinter. This isn't the smallest one we could write, but has enough to illustrate some key concepts you'll need to know.

from tkinter import *
from tkinter import ttk
root = Tk()
frm = ttk.Frame(root, padding=10)
frm.grid()
ttk.Label(frm, text="Hello World!").grid(column=0, row=0)
ttk.Button(frm, text="Quit", command=root.destroy).grid(column=1, row=0)
root.mainloop()

After the imports, the next line creates an instance of the Tk class, which initializes Tk and creates its associated Tcl interpreter. It also creates a toplevel window, known as the root window, which serves as the main window of the application.

The following line creates a frame widget, which in this case will contain a label and a button we'll create next. The frame is fit inside the root window.

The next line creates a label widget holding a static text string. The grid() method is used to specify the relative layout (position) of the label within its containing frame widget, similar to how tables in HTML work.

A button widget is then created, and placed to the right of the label. When pressed, it will call the destroy() method of the root window.

Finally, the mainloop() method puts everything on the display, and responds to user input until the program terminates.

Important Tk Concepts?

Even this simple program illustrates the following key Tk concepts:

widgets

A Tkinter user interface is made up of individual widgets. Each widget is represented as a Python object, instantiated from classes like ttk.Frame, ttk.Label, and ttk.Button.

widget hierarchy

Widgets are arranged in a hierarchy. The label and button were contained within a frame, which in turn was contained within the root window. When creating each child widget, its parent widget is passed as the first argument to the widget constructor.

configuration options

Widgets have configuration options, which modify their appearance and behavior, such as the text to display in a label or button. Different classes of widgets will have different sets of options.

geometry management

Widgets aren't automatically added to the user interface when they are created. A geometry manager like grid controls where in the user interface they are placed.

event loop

Tkinter reacts to user input, changes from your program, and even refreshes the display only when actively running an event loop. If your program isn't running the event loop, your user interface won't update.

Understanding How Tkinter Wraps Tcl/Tk?

When your application uses Tkinter's classes and methods, internally Tkinter is assembling strings representing Tcl/Tk commands, and executing those commands in the Tcl interpreter attached to your applicaton's Tk instance.

Whether it's trying to navigate reference documentation, trying to find the right method or option, adapting some existing code, or debugging your Tkinter application, there are times that it will be useful to understand what those underlying Tcl/Tk commands look like.

To illustrate, here is the Tcl/Tk equivalent of the main part of the Tkinter script above.

ttk::frame .frm -padding 10
grid .frm
grid [ttk::label .frm.lbl -text "Hello World!"] -column 0 -row 0
grid [ttk::button .frm.btn -text "Quit" -command "destroy ."] -column 1 -row 0

Tcl's syntax is similar to many shell languages, where the first word is the command to be executed, with arguments to that command following it, separated by spaces. Without getting into too many details, notice the following:

  • The commands used to create widgets (like ttk::frame) correspond to widget classes in Tkinter.

  • Tcl widget options (like -text) correspond to keyword arguments in Tkinter.

  • Widgets are referred to by a pathname in Tcl (like .frm.btn), whereas Tkinter doesn't use names but object references.

  • A widget's place in the widget hierarchy is encoded in its (hierarchical) pathname, which uses a . (dot) as a path separator. The pathname for the root window is just . (dot). In Tkinter, the hierarchy is defined not by pathname but by specifying the parent widget when creating each child widget.

  • Operations which are implemented as separate commands in Tcl (like grid or destroy) are represented as methods on Tkinter widget objects. As you'll see shortly, at other times Tcl uses what appear to be method calls on widget objects, which more closely mirror what would is used in Tkinter.

How do I...? What option does...??

If you're not sure how to do something in Tkinter, and you can't immediately find it in the tutorial or reference documentation you're using, there are a few strategies that can be helpful.

First, remember that the details of how individual widgets work may vary across different versions of both Tkinter and Tcl/Tk. If you're searching documentation, make sure it corresponds to the Python and Tcl/Tk versions installed on your system.

When searching for how to use an API, it helps to know the exact name of the class, option, or method that you're using. Introspection, either in an interactive Python shell or with print(), can help you identify what you need.

To find out what configuration options are available on any widget, call its configure() method, which returns a dictionary containing a variety of information about each object, including its default and current values. Use keys() to get just the names of each option.

btn = ttk.Button(frm, ...)
print(btn.configure().keys())

As most widgets have many configuration options in common, it can be useful to find out which are specific to a particular widget class. Comparing the list of options to that of a simpler widget, like a frame, is one way to do that.

print(set(btn.configure().keys()) - set(frm.configure().keys()))

Similarly, you can find the available methods for a widget object using the standard dir() function. If you try it, you'll see there are over 200 common widget methods, so again identifying those specific to a widget class is helpful.

print(dir(btn))
print(set(dir(btn)) - set(dir(frm)))

線程模型?

Python 和 Tcl/Tk 的線程模型大不相同,而 tkinter 則會(huì)試圖進(jìn)行調(diào)和。若要用到線程,可能需要注意這一點(diǎn)。

一個(gè) Python 解釋器可能會(huì)關(guān)聯(lián)很多線程。在 Tcl 中,可以創(chuàng)建多個(gè)線程,但每個(gè)線程都關(guān)聯(lián)了單獨(dú)的 Tcl 解釋器實(shí)例。線程也可以創(chuàng)建一個(gè)以上的解釋器實(shí)例,盡管每個(gè)解釋器實(shí)例只能由創(chuàng)建它的那個(gè)線程使用。

Each Tk object created by tkinter contains a Tcl interpreter. It also keeps track of which thread created that interpreter. Calls to tkinter can be made from any Python thread. Internally, if a call comes from a thread other than the one that created the Tk object, an event is posted to the interpreter's event queue, and when executed, the result is returned to the calling Python thread.

Tcl/Tk 應(yīng)用程序通常是事件驅(qū)動(dòng)的,這意味著在完成初始化以后,解釋器會(huì)運(yùn)行一個(gè)事件循環(huán)(即 Tk.mainloop())并對(duì)事件做出響應(yīng)。因?yàn)樗菃尉€程的,所以事件處理程序必須快速響應(yīng),否則會(huì)阻塞其他事件的處理。為了避免阻塞,不應(yīng)在事件處理程序中執(zhí)行任何耗時(shí)很久的計(jì)算,而應(yīng)利用計(jì)時(shí)器將任務(wù)分塊,或者在其他線程中運(yùn)行。而其他很多工具包的 GUI 是在一個(gè)完全獨(dú)立的線程中運(yùn)行的,獨(dú)立于包括事件處理程序在內(nèi)的所有代碼。

如果 Tcl 解釋器沒有運(yùn)行事件循環(huán)并處理解釋器事件,則除運(yùn)行 Tcl 解釋器的線程外,任何其他線程發(fā)起的 tkinter 調(diào)用都會(huì)失敗。

存在一些特殊情況:

  • Tcl/Tk 庫可編譯為不支持多線程的版本。這時(shí) tkinter 會(huì)從初始 Python 線程調(diào)用底層庫,即便那不是創(chuàng)建 Tcl 解釋器的線程。會(huì)有一個(gè)全局鎖來確保每次只會(huì)發(fā)生一次調(diào)用。

  • 雖然 tkinter 允許創(chuàng)建一個(gè)以上的 Tk 實(shí)例(都帶有自己的解釋器),但所有屬于同一線程的解釋器均會(huì)共享同一個(gè)事件隊(duì)列,這樣很快就會(huì)一團(tuán)糟。在實(shí)際編程時(shí),一次創(chuàng)建的 Tk 實(shí)例不要超過一個(gè)。否則最好在不同的線程中創(chuàng)建,并確保運(yùn)行的是支持多線程的 Tcl/Tk 版本。

  • 為了防止 Tcl 解釋器重新進(jìn)入事件循環(huán),阻塞事件處理程序并不是唯一的做法。甚至可以運(yùn)行多個(gè)嵌套的事件循環(huán),或者完全放棄事件循環(huán)。如果在處理事件或線程時(shí)碰到棘手的問題,請(qǐng)小心這些可能的事情。

  • 有幾個(gè) tkinter 函數(shù),目前只在創(chuàng)建 Tcl 解釋器的線程中調(diào)用才行。

快速參考?

可選配置項(xiàng)?

配置參數(shù)可以控制組件顏色和邊框?qū)挾鹊???赏ㄟ^三種方式進(jìn)行設(shè)置:

在對(duì)象創(chuàng)建時(shí),使用關(guān)鍵字參數(shù)
fred = Button(self, fg="red", bg="blue")
在對(duì)象創(chuàng)建后,將參數(shù)名用作字典索引
fred["fg"] = "red"
fred["bg"] = "blue"
利用 config() 方法修改對(duì)象的多個(gè)屬性
fred.config(fg="red", bg="blue")

關(guān)于這些參數(shù)及其表現(xiàn)的完整解釋,請(qǐng)參閱 Tk 手冊(cè)中有關(guān)組件的 man 幫助頁。

請(qǐng)注意,man 手冊(cè)頁列出了每個(gè)部件的“標(biāo)準(zhǔn)選項(xiàng)”和“組件特有選項(xiàng)”。前者是很多組件通用的選項(xiàng)列表,后者是該組件特有的選項(xiàng)。標(biāo)準(zhǔn)選項(xiàng)在 options(3) man 手冊(cè)中有文檔。

本文沒有區(qū)分標(biāo)準(zhǔn)選項(xiàng)和部件特有選項(xiàng)。有些選項(xiàng)不適用于某類組件。組件是否對(duì)某選項(xiàng)做出響應(yīng),取決于組件的類別;按鈕組件有一個(gè) command 選項(xiàng),而標(biāo)簽組件就沒有。

組件支持的選項(xiàng)在其手冊(cè)中有列出,也可在運(yùn)行時(shí)調(diào)用 config() 方法(不帶參數(shù))查看,或者通過調(diào)用組件的 keys() 方法進(jìn)行查詢。這些調(diào)用的返回值為字典,字典的鍵是字符串格式的選項(xiàng)名(比如 'relief'),字典的值為五元組。

有些選項(xiàng),比如 bg 是全名通用選項(xiàng)的同義詞(bg 是 “background”的簡(jiǎn)寫)。向 config() 方法傳入選項(xiàng)的簡(jiǎn)稱將返回一個(gè)二元組,而不是五元組。傳回的二元組將包含同義詞的全名和“真正的”選項(xiàng)(比如 ('bg', 'background'))。

索引

含意

示例

0

選項(xiàng)名稱

'relief'

1

數(shù)據(jù)庫查找的選項(xiàng)名稱

'relief'

2

數(shù)據(jù)庫查找的選項(xiàng)類

'Relief'

3

默認(rèn)值

'raised'

4

當(dāng)前值

'groove'

示例:

>>>
>>> print(fred.config())
{'relief': ('relief', 'relief', 'Relief', 'raised', 'groove')}

當(dāng)然,輸出的字典將包含所有可用選項(xiàng)及其值。這里只是舉個(gè)例子。

包裝器?

包裝器是 Tk 的形狀管理機(jī)制之一。 形狀(geometry )管理器用于指定多個(gè)部件在容器(共同的 組件)內(nèi)的相對(duì)位置。與更為麻煩的 定位器 相比(不太常用,這里不做介紹),包裝器可接受定性的相對(duì)關(guān)系—— 上面左邊 、填充 等,并確定精確的位置坐標(biāo)。

部件的大小都由其內(nèi)部的 “從屬部件” 的大小決定。包裝器用于控制從屬部件在主部件中出現(xiàn)的位置??梢园巡考肟蚣?,再把框架包入其他框架中,搭建出所需的布局。此外,只要完成了包裝,組件的布局就會(huì)進(jìn)行動(dòng)態(tài)調(diào)整,以適應(yīng)布局參數(shù)的變化。

請(qǐng)注意,只有用形狀管理器指定幾何形狀后,部件才會(huì)顯示出來。忘記設(shè)置形狀參數(shù)是新手常犯的錯(cuò)誤,驚訝于創(chuàng)建完部件卻啥都沒出現(xiàn)。部件只有在應(yīng)用了類似于打包器的 pack() 方法之后才會(huì)顯示在屏幕上。

調(diào)用 pack() 方法時(shí)可以給出由關(guān)鍵字/參數(shù)值組成的鍵值對(duì),以便控制組件在其容器中出現(xiàn)的位置,以及主程序窗口大小變動(dòng)時(shí)的行為。下面是一些例子:

fred.pack()                     # defaults to side = "top"
fred.pack(side="left")
fred.pack(expand=1)

包裝器的參數(shù)?

關(guān)于包裝器及其可接受的參數(shù),更多信息請(qǐng)參閱 man 手冊(cè)和 John Ousterhout 書中的第 183 頁。

anchor

anchor 類型。 表示包裝器要放置的每個(gè)從屬組件的位置。

expand

布爾型,01 。

fill

合法值為:'x' 、'y' 、'both' 、'none'。

ipadx 和 ipady

距離值,指定從屬部件的內(nèi)邊距。

padx 和 pady

距離值,指定從屬部件的外邊距。

side

合法值為:'left'、 'right''top'、 'bottom'。

部件與變量的關(guān)聯(lián)?

通過一些特定參數(shù),某些組件(如文本輸入組件)的當(dāng)前設(shè)置可直接與應(yīng)用程序的變量關(guān)聯(lián)。這些參數(shù)包括 variable 、 textvariableonvalue 、 offvaluevalue。這種關(guān)聯(lián)是雙向的:只要這些變量因任何原因發(fā)生變化,其關(guān)聯(lián)的部件就會(huì)更新以反映新的參數(shù)值。

不幸的是,在目前 tkinter 的實(shí)現(xiàn)代碼中,不可能通過 variabletextvariable 參數(shù)將任意 Python 變量移交給組件。變量只有是 tkinter 中定義的 Variable 類的子類,才能生效。

已經(jīng)定義了很多有用的 Variable 子類: StringVar 、 IntVar 、DoubleVarBooleanVar。調(diào)用 get() 方法可以讀取這些變量的當(dāng)前值;調(diào)用 set() 方法則可改變變量值。只要遵循這種用法,組件就會(huì)保持跟蹤變量的值,而不需要更多的干預(yù)。

例如:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master):
        super().__init__(master)
        self.pack()

        self.entrythingy = tk.Entry()
        self.entrythingy.pack()

        # Create the application variable.
        self.contents = tk.StringVar()
        # Set it to some value.
        self.contents.set("this is a variable")
        # Tell the entry widget to watch this variable.
        self.entrythingy["textvariable"] = self.contents

        # Define a callback for when the user hits return.
        # It prints the current value of the variable.
        self.entrythingy.bind('<Key-Return>',
                             self.print_contents)

    def print_contents(self, event):
        print("Hi. The current entry content is:",
              self.contents.get())

root = tk.Tk()
myapp = App(root)
myapp.mainloop()

窗口管理器?

Tk 有個(gè)實(shí)用命令 wm,用于與窗口管理器進(jìn)行交互。wm 命令的參數(shù)可用于控制標(biāo)題、位置、圖標(biāo)之類的東西。在 tkinter 中,這些命令已被實(shí)現(xiàn)為 Wm 類的方法。頂層部件是 Wm 類的子類,所以可以直接調(diào)用 Wm 的這些方法。

要獲得指定部件所在的頂層窗口,通常只要引用該部件的主窗口即可。當(dāng)然,如果該部件是包裝在框架內(nèi)的,那么主窗口不代表就是頂層窗口。為了獲得任意組件所在的頂層窗口,可以調(diào)用 _root() 方法。該方法以下劃線開頭,表明其為 Python 實(shí)現(xiàn)的代碼,而非 Tk 提供的某個(gè)接口。

以下是一些典型用法:

import tkinter as tk

class App(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.pack()

# create the application
myapp = App()

#
# here are method calls to the window manager class
#
myapp.master.title("My Do-Nothing Application")
myapp.master.maxsize(1000, 400)

# start the program
myapp.mainloop()

Tk 參數(shù)的數(shù)據(jù)類型?

anchor

合法值是羅盤的方位點(diǎn):"n" 、"ne" 、"e" 、"se" 、"s" 、"sw""w" 、"nw""center" 。

bitmap

內(nèi)置已命名的位圖有八個(gè):'error''gray25' 、'gray50' 、'hourglass'、 'info' 、'questhead' 、'question' 、'warning' 。若要指定位圖的文件名,請(qǐng)給出完整路徑,前面加一個(gè) @,比如 "@/usr/contrib/bitmap/gumby.bit"

boolean

可以傳入整數(shù) 0 或 1,或是字符串 "yes""no"

callback -- 回調(diào)

指任何無需調(diào)用參數(shù)的 Python 函數(shù)。 例如:

def print_it():
    print("hi there")
fred["command"] = print_it
color

Colors can be given as the names of X colors in the rgb.txt file, or as strings representing RGB values in 4 bit: "#RGB", 8 bit: "#RRGGBB", 12 bit: "#RRRGGGBBB", or 16 bit: "#RRRRGGGGBBBB" ranges, where R,G,B here represent any legal hex digit. See page 160 of Ousterhout's book for details.

cursor

可采用 cursorfont.h 中的標(biāo)準(zhǔn)光標(biāo)名稱,去掉 XC_ 前綴。 比如要獲取一個(gè)手形光標(biāo)(XC_hand2),可以用字符串 "hand2"。也可以指定自己的位圖和掩碼文件作為光標(biāo)。參見 Ousterhout 書中的第 179 頁。

distance

屏幕距離可以用像素或絕對(duì)距離來指定。像素是數(shù)字,絕對(duì)距離是字符串,后面的字符表示單位:c 是厘米,i 是英寸,m 是毫米,p 則表示打印機(jī)的點(diǎn)數(shù)。例如,3.5 英寸可表示為 "3.5i"。

font

Tk 采用一串名稱的格式表示字體,例如 {courier 10 bold}。正數(shù)的字體大小以點(diǎn)為單位,負(fù)數(shù)的大小以像素為單位。

geometry

這是一個(gè) widthxheight 形式的字符串,其中寬度和高度對(duì)于大多數(shù)部件來說是以像素為單位的(對(duì)于顯示文本的部件來說是以字符為單位的)。例如:fred["geometry"] = "200x100"。

justify

合法的值為字符串: "left" 、 "center""right""fill" 。

region

這是包含四個(gè)元素的字符串,以空格分隔,每個(gè)元素是表示一個(gè)合法的距離值(見上文)。例如:"2 3 4 5" 、 "3i 2i 4.5i 2i""3c 2c 4c 10.43c" 都是合法的區(qū)域值。

relief

決定了組件的邊框樣式。 合法值包括:"raised"、 "sunken""flat" 、"groove""ridge" 。

scrollcommand

這幾乎就是帶滾動(dòng)條部件的 set() 方法,但也可是任一只有一個(gè)參數(shù)的部件方法。

wrap

只能是以下值之一:"none" 、 "char" 、 "word"

綁定和事件?

部件命令中的 bind 方法可覺察某些事件,并在事件發(fā)生時(shí)觸發(fā)一個(gè)回調(diào)函數(shù)。bind 方法的形式是:

def bind(self, sequence, func, add=''):

其中:

sequence

is a string that denotes the target kind of event. (See the bind(3tk) man page, and page 201 of John Ousterhout's book, Tcl and the Tk Toolkit (2nd edition), for details).

func

是帶有一個(gè)參數(shù)的 Python 函數(shù),發(fā)生事件時(shí)將會(huì)調(diào)用。傳入的參數(shù)為一個(gè) Event 實(shí)例。(以這種方式部署的函數(shù)通常稱為 回調(diào)函數(shù)。)

add

可選項(xiàng), '''+' 。傳入空字符串表示本次綁定將替換與此事件關(guān)聯(lián)的其他所有綁定。傳遞 '+' 則意味著加入此事件類型已綁定函數(shù)的列表中。

例如:

def turn_red(self, event):
    event.widget["activeforeground"] = "red"

self.button.bind("<Enter>", self.turn_red)

請(qǐng)注意,在 turn_red() 回調(diào)函數(shù)中如何訪問事件的 widget 字段。該字段包含了捕獲 X 事件的控件。下表列出了事件可供訪問的其他字段,及其在 Tk 中的表示方式,這在查看 Tk 手冊(cè)時(shí)很有用處。

Tk

Tkinter 事件字段

Tk

Tkinter 事件字段

%f

focus

%A

char

%h

height

%E

send_event

%k

keycode

%K

keysym

%s

state

%N

keysym_num

%t

time

%T

type

%w

width

%W

widget

%x

x

%X

x_root

%y

y

%Y

y_root

index 參數(shù)?

很多控件都需要傳入 index 參數(shù)。該參數(shù)用于指明 Text 控件中的位置,或指明 Entry 控件中的字符,或指明 Menu 控件中的菜單項(xiàng)。

Entry 控件的索引(index、view index 等)

Entry 控件帶有索引屬性,指向顯示文本中的字符位置。這些 tkinter 函數(shù)可用于訪問文本控件中的這些特定位置:

Text 控件的索引

Text 控件的索引語法非常復(fù)雜,最好還是在 Tk 手冊(cè)中查看。

Menu 索引(menu.invoke()、menu.entryconfig() 等)

菜單的某些屬性和方法可以操縱特定的菜單項(xiàng)。只要屬性或參數(shù)需要用到菜單索引,就可用以下方式傳入:

  • 一個(gè)整數(shù),指的是菜單項(xiàng)的數(shù)字位置,從頂部開始計(jì)數(shù),從 0 開始;

  • 字符串 "active",指的是當(dāng)前光標(biāo)所在的菜單;

  • 字符串 "last",指的是上一個(gè)菜單項(xiàng);

  • 帶有 @ 前綴的整數(shù),比如 @6,這里的整數(shù)解釋為菜單坐標(biāo)系中的 y 像素坐標(biāo);

  • 表示沒有任何菜單條目的字符串 "none" 經(jīng)常與 menu.activate() 一同被用來停用所有條目,以及 ——

  • 與菜單項(xiàng)的文本標(biāo)簽進(jìn)行模式匹配的文本串,從菜單頂部掃描到底部。請(qǐng)注意,此索引類型是在其他所有索引類型之后才會(huì)考慮的,這意味著文本標(biāo)簽為 last、activenone 的菜單項(xiàng)匹配成功后,可能會(huì)視為這些單詞文字本身。

圖片?

通過 tkinter.Image 的各種子類可以創(chuàng)建相應(yīng)格式的圖片:

  • BitmapImage 對(duì)應(yīng) XBM 格式的圖片。

  • PhotoImage 對(duì)應(yīng) PGM、PPM、GIF 和 PNG 格式的圖片。后者自 Tk 8.6 開始支持。

這兩種圖片可通過 filedata 屬性創(chuàng)建的(也可能由其他屬性創(chuàng)建)。

然后可在某些支持 image 屬性的控件中(如標(biāo)簽、按鈕、菜單)使用圖片對(duì)象。這時(shí),Tk 不會(huì)保留對(duì)圖片對(duì)象的引用。當(dāng)圖片對(duì)象的最后一個(gè) Python 引用被刪除時(shí),圖片數(shù)據(jù)也會(huì)刪除,并且 Tk 會(huì)在用到圖片對(duì)象的地方顯示一個(gè)空白框。

參見

Pillow 包增加了對(duì) BMP、JPEG、TIFF 和 WebP 等格式的支持。

文件處理程序?

Tk 允許為文件操作注冊(cè)和注銷一個(gè)回調(diào)函數(shù),當(dāng)對(duì)文件描述符進(jìn)行 I/O 時(shí),Tk 的主循環(huán)會(huì)調(diào)用該回調(diào)函數(shù)。每個(gè)文件描述符只能注冊(cè)一個(gè)處理程序。示例代碼如下:

import tkinter
widget = tkinter.Tk()
mask = tkinter.READABLE | tkinter.WRITABLE
widget.tk.createfilehandler(file, mask, callback)
...
widget.tk.deletefilehandler(file)

在 Windows 系統(tǒng)中不可用。

由于不知道可讀取多少字節(jié),你可能不希望使用 BufferedIOBaseTextIOBaseread()readline() 方法,因?yàn)檫@些方法必須讀取預(yù)定數(shù)量的字節(jié)。 對(duì)于套接字,可使用 recv()recvfrom() 方法;對(duì)于其他文件,可使用原始讀取方法或 os.read(file.fileno(), maxbytecount)。

Widget.tk.createfilehandler(file, mask, func)?

注冊(cè)文件處理程序的回調(diào)函數(shù) funcfile 參數(shù)可以是具備 fileno() 方法的對(duì)象(例如文件或套接字對(duì)象),也可以是整數(shù)文件描述符。 mask 參數(shù)是下述三個(gè)常量的邏輯“或”組合?;卣{(diào)函數(shù)將用以下格式調(diào)用:

callback(file, mask)
Widget.tk.deletefilehandler(file)?

注銷文件處理函數(shù)。

tkinter.READABLE?
tkinter.WRITABLE?
tkinter.EXCEPTION?

Constants used in the mask arguments.