2017年1月19日17:23:55

开始阅读An Introduction To Tkinter,了解TKinter是什么。由于自己当前Windows下使用的是Python 2.7,所以一同参照Python 2.7的Graphical User Interfaces with Tk

阅读之前,先给自己设定两个疑问,带着疑问去找答案:

  • 疑问一:Tkinter是什么?
  • 疑问二:Tkinter与Python有什么关系?

第一个问题在阅读官方文档的时候解决了,在第一句话:

Tk/Tcl has long been an integral part of Python. It provides a robust and platform independent windowing toolkit, that is available to Python programmers using the Tkinter module, and its extensions, the Tix and the ttk modules.

也就是说TKinter是Python基于Tk/Tcl封装的跨平台的窗体程序(也就是带有GUI的程序)开发套件,至于Tk/Tcl是什么,可以看这里。很显然,TKinter是Python的默认GUI开发软件包,但你还有很多其他选择

明白了TKinter是什么之后,下一步是具体的例子来辅助窗体程序的建立,这个时候An Introduction To Tkinter就比Graphical User Interfaces with Tk来得更好了,因为它图文并茂,我觉得按照它上面的例子我很快就可以完成“生成窗口”这个子任务。

第一个问题

按照教程上面敲进了示例代码,运行得到:

lianbche@5CG44636XG D:\Learning\git\Py103\Chap2\project
> python Section2_1_01_TKinterTest.py
Traceback (most recent call last):
  File "Section2_1_01_TKinterTest.py", line 1, in <module>
    from TKinter import *
ImportError: No module named TKinter

看起来是找不到"TKinter"。怎么办?搜索关键字“ImportError: No module named TKinter”。在阅读stackoverflow上一个问题ImportError: No module named 'Tkinter' [closed]的时候看到了如下代码,其中的"Tkinter"与"tkinter"让我想起了前面留意过“Tkinter”中的第二个字母大小写的问题,赶紧回去检查一遍,再测试,果然是这个拼写问题

try:
    # for Python2
    from Tkinter import *   ## notice capitalized T in Tkinter
except ImportError:
    # for Python3
    from tkinter import *   ## notice lowercase 't' in tkinter here

NOTE: 对于每个Tkinter程序必须先创建一个root widget,之后才能创建其他的widget。

简单窗体

在《An Introduction To Tkinter》的第二个例子“Hello, Again”当中,已经可以掌握到三个关键的知识点:

  1. 创建出按钮。
  2. 窗体的退出。
  3. 将按钮的点击行为与函数捆绑在一起。

所以,根据它们可以写作出第一个简单版本的窗体。代码如下:

from Tkinter import *

class App:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.quit = Button(frame, text="QUIT", fg="red", command=frame.quit)
        self.quit.pack(side=LEFT)

        self.history = Button(frame, text="history", command=self.history)
        self.history.pack(side=LEFT)

        self.help = Button(frame, text="help", command=self.help)
        self.help.pack(side=LEFT)

    def history(self):
        print "History."
    def help(self):
        print "Help."

root = Tk()

app = App(root)

root.mainloop()
root.destroy()

运行效果图:

这个窗体很简单,有几个特点:

  • quit的功能已经实现。
  • 它太小了。
  • 与任务描述中的交付成品相比,没有输入文字的地方。

results matching ""

    No results matching ""