已获原作者授权. 原系列地址: Python Tkinter
Hello Tkinter Label
下面我们将以 Tkinter 中最简单的控件: Label 控件, 开始这个系列的教程. 在 Tkinter 中, Label 控件用以显示文字和图片. Label 通常被用来展示信息, 而非与用户交互. (译者注: Label 也可以绑定点击等事件, 只是通常不这么用).
程序员的教程, 怎么能少了 Hello World . 我们尊重这个传统, 但我们不说 Hello World, 让我们来秀出 Hello Tkinter 吧.
下面的 Python 脚本用 Tkinter 创建了一个带有 "Hello Tkinter" 字样的窗口. 你可以在 Python 的命令行解释器中逐行输入下面的脚本, 也可以将之存入一份文件, 比如 hello.py .
from Tkinter import *
# if you are working under Python 3, comment the previous line and comment out the following line
#from tkinter import *
root = Tk()
w = Label(root, text="Hello Tkinter!")
w.pack()
root.mainloop()
运行例子
如果你将上述脚本存入文件 hello.py, 那么可以这样启动它:
$ python hello.py
如果你在 Linux Gnome 环境下运行上述命令, 会显示如下窗口:
在 Windows 系统下是这个样子: