Python支持多種圖形界面的第三方庫,包括:
等等。
但是Python自帶的庫是支持Tk的Tkinter,使用Tkinter,無需安裝任何包,就可以直接使用。本章簡單介紹如何使用Tkinter進(jìn)行GUI編程。
Tkinter
我們來梳理一下概念:
所以,我們的代碼只需要調(diào)用Tkinter提供的接口就可以了。
第一個GUI程序
使用Tkinter十分簡單,我們來編寫一個GUI版本的“Hello, world!”。
第一步是導(dǎo)入Tkinter包的所有內(nèi)容:
from Tkinter import *
第二步是從Frame派生一個Application類,這是所有Widget的父容器:
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()
在GUI中,每個Button、Label、輸入框等,都是一個Widget。Frame則是可以容納其他Widget的Widget,所有的Widget組合起來就是一棵樹。
pack()方法把Widget加入到父容器中,并實現(xiàn)布局。pack()是最簡單的布局,grid()可以實現(xiàn)更復(fù)雜的布局。
在createWidgets()方法中,我們創(chuàng)建一個Label和一個Button,當(dāng)Button被點擊時,觸發(fā)self.quit()使程序退出。
第三步,實例化Application,并啟動消息循環(huán):
app = Application()# 設(shè)置窗口標(biāo)題:app.master.title('Hello World')# 主消息循環(huán):app.mainloop()
GUI程序的主線程負(fù)責(zé)監(jiān)聽來自操作系統(tǒng)的消息,并依次處理每一條消息。因此,如果消息處理非常耗時,就需要在新線程中處理。
運(yùn)行這個GUI程序,可以看到下面的窗口:
點擊“Quit”按鈕或者窗口的“x”結(jié)束程序。
輸入文本
我們再對這個GUI程序改進(jìn)一下,加入一個文本框,讓用戶可以輸入文本,然后點按鈕后,彈出消息對話框。
from Tkinter import *import tkMessageBoxclass 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)
當(dāng)用戶點擊按鈕時,觸發(fā)hello(),通過self.nameInput.get()獲得用戶輸入的文本后,使用tkMessageBox.showinfo()可以彈出消息對話框。
程序運(yùn)行結(jié)果如下:
小結(jié)
Python內(nèi)置的Tkinter可以滿足基本的GUI程序的要求,如果是非常復(fù)雜的GUI程序,建議用操作系統(tǒng)原生支持的語言和庫來編寫。
源碼參考:https://github.com/michaelliao/learn-python/tree/master/gui