EasyGui就是一個簡單的文字交互界面模塊,從今天開始來開始學習Tkinter
Tkinter是Python標准的Gui庫,它實際是建立在Tk技術上的,Tk最初是為Tcl(一門工具名語言)所涉及的,但由於其可移植性和靈活性高,加上非常容易使用,因此它逐漸被移植到許多腳本語言中,包括Perl、Ruby和Python。
所以 TK + interface = Tkinter
Tkinter是Python默認的GUI庫。像IDLE就是用Tkinter設計出來的,因此直接導入Tkinter模塊就可以了。
>>> import tkinter
>>>
注:我安裝的python版本是3.6的,所以不需要單獨安裝Tkinter,但是這里也備注下,如果是2.7版本就需要安裝,並linux系統下,安裝命令為:
apt install python - tk
yum imstall python - tools
Tkinter最初體驗
我們來以一個列子進入Tkinter學習吧。
import tkinter as tk root = tk.Tk() #創建一個主窗口,用於容納整個GUI程序 root.title("study python") #設置主窗口標題欄
#添加一個Label組件,Label組件是GUI程序中常用組件之一
#Label組件可以顯示文本、圖標或圖片
#在這里我們讓他顯示指定的文本 thelable = tk.Label(root,text="這是我第一個tkinter程序窗口")
#然后調用Label組件的pack()方法,用於自動調節組件自身的尺寸 thelable.pack()
#注意,這個時候窗口還不會顯示的。。。
#除非執行下面的這段代碼,進入消息循環 root.mainloop()
執行結果
tkinter.mainloop()通常是程序的最后一行代碼,執行后程序進入主事件循環。學習過界面的都知道一句名言:“Don't call me,I will can you.”就是一旦進入主事件循環,就由Tkinter掌握一起了。
進階版本
如果要寫一個大的程序就需要把代碼進行封裝,在面向對象的語言中,就是封裝成類,來看進階版的例子。
1 import tkinter as tk 2 3 class App(): 4 def __init__(self,root): 5 frame = tk.Frame(root)#創建框架,然后在里面添加一個Button按鈕,框架一般是用於在復雜的布局找你起到將組件分組作用 6 frame.pack() 7 self.hi_there = tk.Button(frame,text="歡迎學習python",fg="bule",command=self.say_hi) #創建一個按鈕組件,fg=foreground的縮寫,就是設置前景色 8 self.hi_there.pack(side=tk.LEFT) 9 def say_hi(self): 10 print("python3學習要循序漸進") 11 12 root = tk.Tk() 13 app = App(root) 14 root.mainloop()
執行結果圖:
程序跑起來,在窗口中出現“歡迎學習python”,單擊后在IDIE接收到反饋信息,反饋信息為:python3學習要循序漸進.
可以通過修改pack()方法的side參數,參數可以設置LEFT、RIGHT、TOP和TOTTOM四個方位,默認設置是:side=tkinter.TOP
例如可以修改為左對齊,frame.pack(side=tk.LEFT),修改后程序如圖:
如果想讓按鈕靠近中間位置,可以通過設置pack()方法的padx和pady參數自定義按鈕的偏移位置:
frame.pack(side=tk.LEFT,padx=100,pady=100)
按鈕也可以設置背景色,需要用到bg參數,就是background背景的縮寫:
self.hi_there = tk.Button(frame, text="歡迎學習python",fg="blue",bg="black", command=self.say_hi)
來改版后的完整程序為:
1 import tkinter as tk 2 3 class App(): 4 def __init__(self, root): 5 frame = tk.Frame(root) 6 #frame.pack() 7 # frame.pack(side=tk.LEFT) 8 frame.pack(side=tk.LEFT,padx=100,pady=100) 9 # self.hi_there = tk.Button(frame, text="歡迎學習python",fg="blue", command=self.say_hi) 10 self.hi_there = tk.Button(frame, text="歡迎學習python",fg="blue",bg="black", command=self.say_hi) 11 self.hi_there.pack(side=tk.LEFT) 12 13 def say_hi(self): 14 print("python3學習要循序漸進") 15 16 root = tk.Tk() #創建一個toplevel的根窗口,並把它作為一個參數傳遞給實例化對象app 17 app = App(root) 18 root.mainloop()