tkinter --- Tcl/Tk的Python接口

源代码: Lib/tkinter/


在命令行中运行 python -m tkinter，应该会弹出一个Tk界面的窗口，表明 tkinter 包已经正确安装，而且告诉你 Tcl/Tk 的版本号，通过这个版本号，你就可以参考对应的 Tcl/Tk 文档了。



Python Tkinter 资源

The Python Tkinter Topic Guide 提供了在 Python 中使用 Tk 的很多信息， 同时包含了Tk其他信息的链接。



Tkinter 8.5 参考：一个Python图形用户界面


Tkinter docs from effbot 提供的 tkinter 在线参考资料。

使用 Python 编程

由 Mark Lutz 所著的书籍，对 Tkinter 进行了完美的介绍。

为繁忙的 Python 开发者所准备的现代 Tkinter

由 Mark Rozerman 所著的关于如何使用 Python 和 Tkinter 来搭建有吸引力的和现代化的图形用户界面的书籍

Python 和 Tkinter 编程

作者： John Grayson (ISBN 1-884777-81-3).

Tcl/Tk 文档:

Tk 命令

多数命令以 tkinter 或者 tkinter.ttk 类的形式存在。改变 '8.6' 以匹配所安装的 Tcl/Tk 版本。

Tcl/Tk 最新手册页面 上面最新的 Tcl/Tk 手册。

ActiveState Tcl 主页

Tk/Tcl 的多数开发工作发生在 ActiveState 。

Tcl 及 Tk 工具集

由 Tcl 发明者 John Ousterhout 所著的书籍。

` Tcl 和 Tk 编程实战 <>`_

Brent Welch 所著的百科全局式书籍。

Tkinter 模块

在大多数时候你只需要 tkinter 就足够了，但也有一些额外的模块可供使用。Tk 接口位于一个名字 _tkinter 的二进制模块当中。此模块包含了低层级的 Tk 接口，它不应该被应用程序员所直接使用。它通常是一个共享库（或 DLL），但在某些情况下也可能被静态链接到 Python 解释器。

除了Tk接口， tkinter 也包含了若干 Python 模块，tkinter.constants 是其中最重要的。导入 tkinter 会自动导入 tkinter.constants ，所以，要使用 Tkinter 通常你只需要一条简单的 import 语句:

import tkinter


from tkinter import *

Tk 类被初始化时无参数。此时会创建一个 Tk 顶级控件，通常是应用程序的主窗口。每个实例都有自己关联的 Tcl 解释器。


Tcl() 函数是一个工厂函数，它创建的对象与 Tk 类创建的对象非常相似，只是它不初始化 Tk 子系统。 在不想创建或无法创建（如没有 X Server 的 Unix/Linux 系统）额外的顶层窗口的环境中驱动 Tcl 解释器时，这一点非常有用。 由 Tcl() 对象创建的对象可以通过调用其 loadtk() 方法来创建顶层窗口（并初始化 Tk 子系统）。



Text widget with a vertical scroll bar built in.








Utilities to help work with fonts.


Access to standard Tk dialog boxes.


Basic dialogs and convenience functions.




Turtle graphics in a Tk window.

Tkinter Life Preserver



  • Tk was written by John Ousterhout while at Berkeley.

  • Tkinter was written by Steen Lumholt and Guido van Rossum.





How To Use This Section


When trying to answer questions of the form "how do I do blah", it is often best to find out how to do "blah" in straight Tk, and then convert this back into the corresponding tkinter call. Python programmers can often guess at the correct Python command by looking at the Tk documentation. This means that in order to use Tkinter, you will have to know a little bit about Tk. This document can't fulfill that role, so the best we can do is point you to the best documentation that exists. Here are some hints:



  • tkinter/ is a last resort for most, but can be a good place to go when nothing else makes sense.

A Simple Hello World Program

import tkinter as tk

class Application(tk.Frame):
    def __init__(self, master=None):
        self.master = master

    def create_widgets(self):
        self.hi_there = tk.Button(self)
        self.hi_there["text"] = "Hello World\n(click me)"
        self.hi_there["command"] = self.say_hi

        self.quit = tk.Button(self, text="QUIT", fg="red",

    def say_hi(self):
        print("hi there, everyone!")

root = tk.Tk()
app = Application(master=root)

A (Very) Quick Look at Tcl/Tk



  • These classes are provided for the purposes of organizing certain functions under one namespace. They aren't meant to be instantiated independently.


  • The Widget class is not meant to be instantiated, it is meant only for subclassing to make "real" widgets (in C++, this is called an 'abstract class').




classCommand newPathname options





configure the widget's appearance and in some cases, its behavior. The options come in the form of a list of flags and values. Flags are preceded by a '-', like Unix shell command flags, and values are put in quotes if they are more than one word.


button   .fred   -fg red -text "hi there"
   ^       ^     \______________________/
   |       |                |
 class    new            options


.fred someAction someOptions




Mapping Basic Tk into Tkinter

Class commands in Tk correspond to class constructors in Tkinter.





                            OR ==>  fred.config(fg="red")


.fred invoke                =====>  fred.invoke()



Handy Reference

Setting Options


At object creation time, using keyword arguments
After object creation, treating the option name like a dictionary index
fred["fg"] = "red"
fred["bg"] = "blue"





Some options, like bg are synonyms for common options with long names (bg is shorthand for "background"). Passing the config() method the name of a shorthand option will return a 2-tuple, not 5-tuple. The 2-tuple passed back will contain the name of the synonym and the "real" option (such as ('bg', 'background')).




















>>> print(fred.config())


The Packer

The packer is one of Tk's geometry-management mechanisms. Geometry managers are used to specify the relative positioning of widgets within their container - their mutual master. In contrast to the more cumbersome placer (which is used less commonly, and we do not cover here), the packer takes qualitative relationship specification - above, to the left of, filling, etc - and works everything out to determine the exact placement coordinates for you.




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

Packer Options

For more extensive information on the packer and the options that it can take, see the man pages and page 183 of John Ousterhout's book.




Boolean, 0 or 1.



ipadx 和 ipady


padx 和 pady




Coupling Widget Variables

The current-value setting of some widgets (like text entry widgets) can be connected directly to application variables by using special options. These options are variable, textvariable, onvalue, offvalue, and value. This connection works both ways: if the variable changes for any reason, the widget it's connected to will be updated to reflect the new value.




import tkinter as tk

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

        self.entrythingy = tk.Entry()

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

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

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

The Window Manager



Here are some examples of typical usage:

import tkinter as tk

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

# 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

Tk Option Data Types







callback -- 回调


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

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.




Screen distances can be specified in either pixels or absolute distances. Pixels are given as numbers and absolute distances as strings, with the trailing character denoting units: c for centimetres, i for inches, m for millimetres, p for printer's points. For example, 3.5 inches is expressed as "3.5i".















Bindings and Events




sequence -- 序列

is a string that denotes the target kind of event. (See the bind man page and page 201 of John Ousterhout's book for details).






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

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

Notice how the widget field of the event is being accessed in the turn_red() callback. This field contains the widget that caught the X event. The following table lists the other event fields you can access, and how they are denoted in Tk, which can be useful when referring to the Tk man pages.


Tkinter Event Field


Tkinter Event Field

































The index Parameter

A number of widgets require "index" parameters to be passed. These are used to point at a specific place in a Text widget, or to particular characters in an Entry widget, or to particular menu items in a Menu widget.

Entry widget indexes (index, view index, etc.)


Text widget indexes







  • An integer preceded by @, as in @6, where the integer is interpreted as a y pixel coordinate in the menu's coordinate system;




Images of different formats can be created through the corresponding subclass of tkinter.Image:

  • BitmapImage for images in XBM format.

  • PhotoImage for images in PGM, PPM, GIF and PNG formats. The latter is supported starting with Tk 8.6.




The Pillow package adds support for formats such as BMP, JPEG, TIFF, and WebP, among others.

File Handlers

Tk allows you to register and unregister a callback function which will be called from the Tk mainloop when I/O is possible on a file descriptor. Only one handler may be registered per file descriptor. Example code:

import tkinter
widget = tkinter.Tk()
mask = tkinter.READABLE | tkinter.WRITABLE, mask, callback)

This feature is not available on Windows.

Since you don't know how many bytes are available for reading, you may not want to use the BufferedIOBase or TextIOBase read() or readline() methods, since these will insist on reading a predefined number of bytes. For sockets, the recv() or recvfrom() methods will work fine; for other files, use raw reads or, maxbytecount)., mask, func)

Registers the file handler callback function func. The file argument may either be an object with a fileno() method (such as a file or socket object), or an integer file descriptor. The mask argument is an ORed combination of any of the three constants below. The callback is called as follows:

callback(file, mask)

Unregisters a file handler.


Constants used in the mask arguments.