Python支持多种图形界面,有:第三方库有Tk、wxWidgets、Qt、GTK等。app
Python自带的库是支持Tk的Tkinter,无需安装任何安装包,就能够直接使用。函数
在Python中使用函数调用Tkinter的接口,而后Tk会调用操做系统提供的本地GUI接口,完成最终的GUI。oop
编写一个简单的GUI:布局
from Tkinter import * class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.helloLabel = Label(self, text='Hello, world!') self.helloLabel.pack() self.quitButton = Button(self, text='Quit', command=self.quit) self.quitButton.pack()
app = Application() # 设置窗口标题: app.master.title('Hello World') # 主消息循环: app.mainloop()
在GUI中,每个按钮、标签、输入框都是一个Widget。Frame是最大的Widget,它能够容纳其余的Widget。学习
pack()方法是将已经建立好的Widget添加到父容器中,它是最简单的布局,grid()能够实现相对复杂的布局。ui
在creatWidgets()方法中,建立的Button被点击时,触发内部的命令self.quit(),使程序退出。spa
还能够增长输入文本的文本框:操作系统
from Tkinter import * import tkMessageBox class Application(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.createWidgets() def createWidgets(self): self.nameInput = Entry(self) self.nameInput.pack() self.alertButton = Button(self, text='Hello', command=self.hello) self.alertButton.pack() def hello(self): name = self.nameInput.get() or 'world' tkMessageBox.showinfo('Message', 'Hello, %s' % name)
当用户点击按钮时,触发hello(),经过self.nameInput.get()得到用户输入的文本后,使用txMessageBox.showinfo()能够弹出消息对话框。3d
注:本文为学习廖雪峰Python入门整理后的笔记code