簡單的python GUI例子


寫一個簡單的界面很容易,即使是什么都不了解的情況下,這個文本轉載了最簡單的界面編寫,下個文本介紹了TK的簡單但具體的應用

 

在python中創建一個窗口,然后顯示出來。

[python]  view plain copy
  1. from Tkinter import *  
  2. root = Tk()  
  3. root.mainloop()  

就3行就能夠把主窗口顯示出來了。root是一個變量名稱,其代表了這個主窗口。以后創建控件的時候指定控件創建在什么窗口之中,就要用這個root來表示了。而Tk()是一個Tkinter庫之中的函數(其實是類的構造函數,構造了一個對象)。而mainloop則是主窗口的成員函數,也就是表示讓這個root工作起來,開始接收鼠標的和鍵盤的操作。你現在就能夠通過鼠標縮放以及關閉這個窗口了。注意到窗口的標題是tk,我們可以進行一些修改

 

[python]  view plain copy
  1. root= Tk(className='bitunion')  

 

然后窗口的標題就變成了bitunion了。下面要作的是把這個窗口的內容填充一下,讓其有一些東西。先加入一個標簽,所謂標簽就是一行字。

[python]  view plain copy
  1. from Tkinter import *  
  2. root = Tk(className='bitunion')  
  3. label = Label(root)  
  4. label['text'] = 'be on your own'  
  5. label.pack()  
  6. root.mainloop()  

我們很驚訝的發現窗口變小了,但是其中多了一行字。變小了是因為窗口中已經放了東西了,python的Tkinter非常智能,能夠根據內容自動縮放,而不用和傳統的windows程序一樣,手工的指定絕對坐標了。對於label,它還是一個變量而已。不過這個變量代表了一個標簽,也就是那一行字。而這個label的創建是用Label,而Label的參數是root表明了這個控件是root主窗口的成員控件,或者說是子窗口。label['text']表示設置這個標簽的text屬性為'be on your own',也就是文字內容了。label.pack和root.mainloop一樣費解,但是內涵一樣深刻。你現在可以簡單理解為把label顯示出來的功能,因為你把pack去掉,那你就看不到東西了。其實pack是和控件的布局排版有關西的。

再添加一個按鈕就能夠有更加豐富的內容了,方法是很類似的。看着吧:

[python]  view plain copy
  1. from Tkinter import *  
  2. root = Tk(className='bitunion')  
  3. label = Label(root)  
  4. label['text'] = 'be on your own'  
  5. label.pack()  
  6. button = Button(root)  
  7. button['text'] = 'change it'  
  8. button.pack()  
  9. root.mainloop()  

只不過把button替換了label而Button替換了Label。注意一下Button和Label這些都是Tkinter這些庫提供的,而button和Button這樣大小寫之間的差別僅僅是巧合,你能夠隨便的給變量取名字,但是Button和Label這些則是需要記住的東西,寫代碼的時候要經常用到的名字。但是點擊按鈕你會比較失望,因為並沒有什么反應。不過也是當然的事情,你並沒有告訴計算機對於這樣一個按鈕的點擊操作需要作出一個什么樣的反應來反饋給用戶。而這個指定作出什么反應的工作只需要一個行,但是作出具體什么樣反應的描述則需要新建一個函數來進行處理。

[python]  view plain copy
  1. from Tkinter import *  
  2. def on_click():  
  3.     label['text'] = 'no way out'  
  4. root = Tk(className='bitunion')  
  5. label = Label(root)  
  6. label['text'] = 'be on your own'  
  7. label.pack()  
  8. button = Button(root)  
  9. button['text'] = 'change it'  
  10. button['command'] = on_click  
  11. button.pack()  
  12. root.mainloop()  

button['command'] = on_click表示對於button(按鈕)的點擊屬性用on_click這個函數來處理。而on_click函數也很簡潔,只是把label的文本重新設置一下。這個完成了一個事件消息的處理,如果用C來寫,需要比這個長更加不好懂的寫法。另外你是否會對on_click中出現label這個變量比較奇怪呢?明明在on_click前面沒有定義label這個變量啊。如果我在C中這么寫程序,編譯器一定會告訴我出錯的。而python是怎么知道label這個變量存在,然后沒有報錯的呢?其實python在你寫的時候根本就不用知道其是否存在,只是要在運行的時候找得到label就可以了。而運行的前后關系,是通過時間來關聯的而不是代碼上前后行的關系。這里由於label = Label(root)先於on_click執行,所以當on_click執行的時候,label就是一個已經定義的變量。如果沒有定義呢?那就報告出錯嘍。

最后一個例子:

[python]  view plain copy
  1. from Tkinter import *  
  2. def on_click():  
  3.     label['text'] = text.get()  
  4.   
  5. root = Tk(className='bitunion')  
  6. label = Label(root)  
  7. label['text'] = 'be on your own'  
  8. label.pack()  
  9. text = StringVar()  
  10. text.set('change to what?')  
  11. entry = Entry(root)  
  12. entry['textvariable'] = text  
  13. entry.pack()  
  14. button = Button(root)  
  15. button['text'] = 'change it'  
  16. button['command'] = on_click  
  17. button.pack()  
  18. root.mainloop()  

這個就比較復雜了。里面有一個StringVar。這個代表一個字符串,但是跟一般字符串不一樣。一般的這樣'dfsdf'的字符串是不可變的,你只能把變量指定為不同的字符串,但是字符串本身的內容是不可改變的。而StringVar則是可變的字符串。所以了set和get來設置和取得其內容。主要是entry(單行輸入框)要求一個這樣的屬性來設置和接收其輸入框的內容。

 

 

用Tkinter實現一個簡單的GUI程序,單擊click按鈕時會在終端打印出’hello world’:

 

[python]  view plain copy
  1. __author__ = 'fyby'  
  2. from Tkinter import *   #引入Tkinter工具包  
  3. def hello():  
  4.     print('hello world!')  
  5.   
  6. win = Tk()  #定義一個窗體  
  7. win.title('Hello World')    #定義窗體標題  
  8. win.geometry('400x200')     #定義窗體的大小,是400X200像素  
  9.   
  10. btn = Button(win, text='Click me', command=hello)  
  11. #注意這個地方,不要寫成hello(),如果是hello()的話,  
  12. #會在mainloop中調用hello函數,  
  13. # 而不是單擊button按鈕時出發事件  
  14. btn.pack(expand=YES, fill=BOTH) #將按鈕pack,充滿整個窗體(只有pack的組件實例才能顯示)  
  15.   
  16. mainloop() #進入主循環,程序運行  

 

 

    當我們寫一個較大的程序時,最好將代碼分成一個或者是幾個類,再看一下Hello World例子

 

[python]  view plain copy
  1. #-*- encoding=UTF-8 -*-  
  2. __author__ = 'fyby'  
  3. from Tkinter import *  
  4. class App:  
  5.     def __init__(self, master):  
  6.         #構造函數里傳入一個父組件(master),創建一個Frame組件並顯示  
  7.         frame = Frame(master)  
  8.         frame.pack()  
  9.         #創建兩個button,並作為frame的一部分  
  10.         self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)  
  11.         self.button.pack(side=LEFT) #此處side為LEFT表示將其放置 到frame剩余空間的最左方  
  12.         self.hi_there = Button(frame, text="Hello", command=self.say_hi)  
  13.         self.hi_there.pack(side=LEFT)  
  14.   
  15.     def say_hi(self):  
  16.         print "hi there, this is a class example!"  
  17.   
  18. win = Tk()  
  19. app = App(win)  
  20. win.mainloop()  

 

    看完了上面兩個無聊的Hello World例子,再來看一個稍微Perfect點的東西吧。Menu組件,自己畫一個像樣點的程序外殼。

 

[python]  view plain copy
  1. #-*- encoding=UTF-8 -*-  
  2. __author__ = 'fyby'  
  3. from Tkinter import *  
  4. class App:  
  5.     def __init__(self, master):  
  6.         #構造函數里傳入一個父組件(master),創建一個Frame組件並顯示  
  7.         frame = Frame(master)  
  8.         frame.pack()  
  9.         #創建兩個button,並作為frame的一部分  
  10.         self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)  
  11.         self.button.pack(side=LEFT) #此處side為LEFT表示將其放置 到frame剩余空間的最左方  
  12.         self.hi_there = Button(frame, text="Hello", command=self.say_hi)  
  13.         self.hi_there.pack(side=LEFT)  
  14.   
  15.     def say_hi(self):  
  16.         print "hi there, this is a class example!"  
  17.   
  18. win = Tk()  
  19. app = App(win)  
  20. win.mainloop()  

 

        這個程序還是有點無趣,因為我們只是創建了一個頂級的導航菜單,點擊后只是在終端中輸出hello而已,下面來創建一個下拉菜單,這樣才像一個正兒八經的應用大笑在下面的這個例子中,會創建三個頂級菜單,每個頂級菜單中都有下拉菜單(用add_command方法創建,最后用add_cascade方法加入到上級菜單中去),為每個下拉選項都綁定一個hello函數,在終端中打印出hello.

        root.quit是退出這個Tk的實例。

 

[python]  view plain copy
  1. #-*- encoding=UTF-8 -*-  
  2. __author__ = 'fyby'  
  3. from Tkinter import *  
  4. root = Tk()  
  5.   
  6. def hello():  
  7.     print('hello')  
  8.   
  9. def about():  
  10.     print('我是開發者')  
  11.   
  12. menubar = Menu(root)  
  13.   
  14. #創建下拉菜單File,然后將其加入到頂級的菜單欄中  
  15. filemenu = Menu(menubar,tearoff=0)  
  16. filemenu.add_command(label="Open", command=hello)  
  17. filemenu.add_command(label="Save", command=hello)  
  18. filemenu.add_separator()  
  19. filemenu.add_command(label="Exit", command=root.quit)  
  20. menubar.add_cascade(label="File", menu=filemenu)  
  21.   
  22. #創建另一個下拉菜單Edit  
  23. editmenu = Menu(menubar, tearoff=0)  
  24. editmenu.add_command(label="Cut", command=hello)  
  25. editmenu.add_command(label="Copy", command=hello)  
  26. editmenu.add_command(label="Paste", command=hello)  
  27. menubar.add_cascade(label="Edit",menu=editmenu)  
  28. #創建下拉菜單Help  
  29. helpmenu = Menu(menubar, tearoff=0)  
  30. helpmenu.add_command(label="About", command=about)  
  31. menubar.add_cascade(label="Help", menu=helpmenu)  
  32.   
  33. #顯示菜單  
  34. root.config(menu=menubar)  
  35.   
  36. mainloop()  

 

 

   寫了這一些,差不多對Tkinter有了一個大體的印象了。在Python中用Tkinter繪制GUI界面還是蠻簡單的。再把上面的例子擴展一下,和Label標簽結合,當單擊about的時候,在窗體上打印About的內容,而不是在終端輸出。將about函數稍微修改一下。單擊about以后將會調用about函數渲染frame繪制一個標簽並顯示其內容。
def about():
    w = Label(root,text="開發者感謝名單\nfuyunbiyi\nfyby尚未出現的女朋友\nhttp://www.programup.com網站")
    w.pack(side=TOP)

 

 

 

Tkinter的提供各種控件,如按鈕,標簽和文本框,一個GUI應用程序中使用。這些控件通常被稱為控件或者部件。

目前有15種Tkinter的部件。我們提出這些部件以及一個簡短的介紹,在下面的表:

Tkinter常用控件

控件 描述
Label Label widget which can display text and bitmaps標簽控件;可以顯示文本和位圖
Button 按鈕控件;在程序中顯示按鈕
Entry Entry widget which allows to display simple text輸入控件;用於顯示簡單的文本內容
Checkbutton Checkbutton widget which is either in on- or off-state多選框控件;用於在程序中提供多項選擇框
Listbox Listbox widget which can display a list of strings.列表框控件;在Listbox窗口小部件是用來顯示一個字符串列表給用戶
Scale Scale widget which can display a numerical scale范圍控件;顯示一個數值刻度,為輸出限定范圍的數字區間
Spinbox 輸入控件;與Entry類似,但是可以指定輸入范圍值
Menu Menu widget which allows to display menu bars, pull-down menus and pop-up menus菜單控件;顯示菜單欄,下拉菜單和彈出菜單
Message Message widget to display multiline text. Obsolete since Label does it too消息控件;用來顯示多行文本,與label比較類似
OptionMenu OptionMenu which allows the user to select a value from a menu.可選菜單控件;允許用戶在菜單中選擇值
Radiobutton Radiobutton widget which shows only one of several buttons in on-state單選按鈕控件;顯示一個單選的按鈕狀態
Frame Frame widget which may contain other widgets and can have a 3D border框架控件;在屏幕上顯示一個矩形區域,多用來作為容器
Toplevel Toplevel widget, e.g. for dialogs.容器控件;用來提供一個單獨的對話框,和Frame比較類似
Text Text widget which can display text in various forms文本控件;用於顯示多行文本
Canvas Canvas widget to display graphical elements like lines or text.畫布控件;顯示圖形元素如線條或文本
Event Container for the properties of an event.事件控件;

標准屬性:

 

標准屬性也就是所有控件的共同屬性,如大小,字體和顏色等等。

屬性 描述
Dimension 控件大小;
Color 控件顏色;
Font 控件字體;
Anchor 錨點;
Relief 控件樣式;
Bitmap 位圖;
Cursor 光標;

 

幾何管理:

Tkinter控件有特定的幾何狀態管理方法,管理整個控件區域組織,一下是Tkinter公開的幾何管理類:包、網格、位置

幾何方法 描述
pack() 包裝;
grid() 網格;
place() 位置;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM