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的Frame類派生出一個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程序