本手册翻译自http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html
1. 一个为Python建造图形用户界面的交互式平台
Tkinter 是为Python设置的一个 GUI (图形用户界面) 组件。本手册的内容是面向运行在Linux下 X Window 系统的 Python 2.7 和 Tkinter 8.5。 你的版本可能与此不同。
参考文献:
-
Fredrik Lundh, Tkinter的作者, 他的 An Introduction to Tkinter有两个版本:更完整的 1999 version and2005 version 其中呈现了一些新的特性。
-
Python 2.7 quick reference: 关于 Python 语言的一般信息.
-
拿一个相当大的应用程序(大约1000行代码)举例说明, 参考 huey: A color and font selection tool. 这个程序的设计示范了怎么样去建立属于你的复合组。
我们将通过查看 Tkinter 的可见部分开始Tkinter: 创建小部件,并安排他们在屏幕上。稍后我们将讨论如何联系表面——应用程序的“前面板”和它背后的逻辑。
2. 一个最小的程序
这是一个很微不足道的 Tkinter 程序,它只包含一个退出按钮:
#!/usr/bin/env python 1 import Tkinter as tk 2 class Application(tk.Frame): 3 def __init__(self, master=None): tk.Frame.__init__(self, master) 4 self.grid() 5 self.createWidgets() def createWidgets(self): self.quitButton = tk.Button(self, text='Quit', command=self.quit) 6 self.quitButton.grid() 7 app = Application() 8 app.master.title('Sample application') 9 app.mainloop() 10
1 | 假设你的系统中正确安装了Python,此行使脚本自动执行。 |
2 | 此行导入Tkinter 的模块到你的程序的名字空间,但将其重命名为 tk 。 |
3 | 您的Application类必须继承自Tkinter的Frame 类。 |
4 | 调用构造函数的父类, Frame 。 |
5 | 必须使应用程序实际上出现在屏幕上。 |
6 | 创建标签为“Quit”的按钮。 |
7 | 把这个按钮放置在应用程序中。 |
8 | 主程序通过实例化 Application 类,在此开始。 |
9 | 此方法调用设置的了应用程序的标题为 “Sample application”. |
10 | 启动应用程序的主循环,等待鼠标和键盘事件。 |