首页 > 代码库 > Python Tkinter学习(1)——第一个Tkinter程序

Python Tkinter学习(1)——第一个Tkinter程序

注:本文可转载,转载请注明出处:http://www.cnblogs.com/collectionne/p/6885066.html。

 

Tkinter介绍

 

Python支持多个图形库,例如Qt、wxWidgets,等等。但是Python的标准GUI库是Tkinter。Tkinter是Tk Interface的缩写。Python提供了tkinter包,里面含有Tkinter接口。

 

开始写程序

 

这一节,我们将会写一个只有一个Quit按钮的Tkinter程序。

 

要使用Tkinter,需要首先导入tkinter包:

 

import tkinter as tk

 

这个import语句的含义是,导入tkinter包,但为tkinter定义了一个别名tk。后面我们可以直接用tk.xxx来访问tkinter.xxx了。

 

然后,我们需要从tkinterFrame类派生出一个Application类:

 

class Application(tk.Frame):

 

然后我们为Application类定义一个构造函数__init__()

 

    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

 

第一句tk.Frame.__init__(self, master),这个语句调用Application的父类Frame的构造函数,初始化Frame

 

第二句self.grid(),通常一个窗口默认是不显示的,grid()方法让窗口能够在屏幕上显示出来。

 

第三句self.createWidgets(),调用后面定义的createWidgets()方法。

 

接下来是createWidgets()函数:

 

    def createWidgets(self):
        self.quitButton = tk.Button(self, text=‘Quit‘, command=self.quit)
        self.quitButton.grid()

 

第一行self.quitButton = tk.Button(self, text=‘Quit‘, command=self.quit),这个quitButton是自己创建的属性,创建一个标签为Quit,点击之后会退出的按钮。

 

第二行self.quitButton.grid(),按钮和窗口一样,默认不显示,调用grid()方法使得按钮显示在窗口上。

 

接下来就到了执行了:

 

app = Application()
app.master.title = ‘Hello Tkinter‘
app.mainloop()

 

第一行app = Application(),创建一个Application对象。

 

第二行app.master.title = ‘Hello Tkinter‘,将窗口标题设置为"Hello Tkinter"。

 

第三行app.mainloop(),开始程序主循环。

Python Tkinter学习(1)——第一个Tkinter程序