Python支持多種圖形界面的第三方庫,包括:
-
Tk
-
wxWidgets
-
Qt
-
GTK
等等。
但是Python自帶的庫是支持Tk的Tkinter,使用Tkinter,無需安裝任何包,就可以直接使用。本章簡單介紹如何使用Tkinter進行GUI編程。
Tkinter
我們來梳理一下概念:
我們編寫的Python代碼會調用內置的Tkinter,Tkinter封裝了訪問Tk的接口;
Tk是一個圖形庫,支持多個操作系統,使用Tcl語言開發;
Tk會調用操作系統提供的本地GUI接口,完成最終的GUI。
所以,我們的代碼只需要調用Tkinter提供的接口就可以了。
第一個GUI程序
使用Tkinter十分簡單,我們來編寫一個GUI版本的“Hello, world!”。
第一步是導入Tkinter包的所有內容:
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加入到父容器中,並實現布局。pack()
是最簡單的布局,grid()
可以實現更復雜的布局。
在createWidgets()
方法中,我們創建一個Label
和一個Button
,當Button被點擊時,觸發self.quit()
使程序退出。
第三步,實例化Application
,並啟動消息循環:
app = Application() # 設置窗口標題: app.master.title('Hello World') # 主消息循環: app.mainloop()
GUI程序的主線程負責監聽來自操作系統的消息,並依次處理每一條消息。因此,如果消息處理非常耗時,就需要在新線程中處理。
運行這個GUI程序,可以看到下面的窗口:
點擊“Quit”按鈕或者窗口的“x”結束程序。
輸入文本
我們再對這個GUI程序改進一下,加入一個文本框,讓用戶可以輸入文本,然后點按鈕后,彈出消息對話框。
from tkinter import * import tkinter.messagebox as messagebox 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' messagebox.showinfo('Message', 'Hello, %s' % name) app = Application() # 設置窗口標題: app.master.title('Hello World') # 主消息循環: app.mainloop()
當用戶點擊按鈕時,觸發hello()
,通過self.nameInput.get()
獲得用戶輸入的文本后,使用tkMessageBox.showinfo()
可以彈出消息對話框。
程序運行結果如下:
小結
Python內置的Tkinter可以滿足基本的GUI程序的要求,如果是非常復雜的GUI程序,建議用操作系統原生支持的語言和庫來編寫。