Tkinter
我們編寫(xiě)的Python代碼會(huì)調(diào)用內(nèi)置的Tkinter础米,Tkinter封裝了訪(fǎng)問(wèn)Tk的接口矫渔;
Tk是一個(gè)圖形庫(kù)汗菜,支持多個(gè)操作系統(tǒng)让禀,使用Tcl語(yǔ)言開(kāi)發(fā);
Tk會(huì)調(diào)用操作系統(tǒng)提供的本地GUI接口陨界,完成最終的GUI巡揍。
所以,我們的代碼只需要調(diào)用Tkinter提供的接口就可以了菌瘪。
第一個(gè)GUI程序
使用Tkinter十分簡(jiǎn)單腮敌,我們來(lái)編寫(xiě)一個(gè)GUI版本的“Hello, world!”阱当。
第一步是導(dǎo)入Tkinter包的所有內(nèi)容:
from tkinter import *
第二步是從Frame派生一個(gè)Application類(lèi),這是所有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中糜工,每個(gè)Button弊添、Label、輸入框等捌木,都是一個(gè)Widget油坝。Frame則是可以容納其他Widget的Widget,所有的Widget組合起來(lái)就是一棵樹(shù)刨裆。
pack()方法把Widget加入到父容器中澈圈,并實(shí)現(xiàn)布局。pack()是最簡(jiǎn)單的布局帆啃,grid()可以實(shí)現(xiàn)更復(fù)雜的布局瞬女。
在createWidgets()方法中,我們創(chuàng)建一個(gè)Label和一個(gè)Button链瓦,當(dāng)Button被點(diǎn)擊時(shí)拆魏,觸發(fā)self.quit()使程序退出。
第三步慈俯,實(shí)例化Application渤刃,并啟動(dòng)消息循環(huán):
app = Application()
設(shè)置窗口標(biāo)題:
app.master.title('Hello World')
主消息循環(huán):
app.mainloop()```
GUI程序的主線(xiàn)程負(fù)責(zé)監(jiān)聽(tīng)來(lái)自操作系統(tǒng)的消息,并依次處理每一條消息贴膘。因此卖子,如果消息處理非常耗時(shí),就需要在新線(xiàn)程中處理刑峡。
運(yùn)行這個(gè)GUI程序洋闽,可以看到下面的窗口:
點(diǎn)擊“Quit”按鈕或者窗口的“x”結(jié)束程序。
輸入文本
我們?cè)賹?duì)這個(gè)GUI程序改進(jìn)一下突梦,加入一個(gè)文本框诫舅,讓用戶(hù)可以輸入文本,然后點(diǎn)按鈕后宫患,彈出消息對(duì)話(huà)框刊懈。
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()
# 設(shè)置窗口標(biāo)題:
app.master.title('Hello World')
# 主消息循環(huán):
app.mainloop()```
當(dāng)用戶(hù)點(diǎn)擊按鈕時(shí),觸發(fā)hello()娃闲,通過(guò)self.nameInput.get()獲得用戶(hù)輸入的文本后虚汛,使用tkMessageBox.showinfo()可以彈出消息對(duì)話(huà)框。
程序運(yùn)行結(jié)果如下:
