Python 支持多種圖形界面的第三方庫,包括html
Python 提供的 Tkinter 模塊,就是 Tk GUI 工具包的接口。python
Tk 是圖形庫,支持多種操做系統,使用 Tcl 語言開發;segmentfault
Tk 會調用操做系統提供的本地 GUI 接口,完成最終的 GUI。微信
因此代碼實現的只須要調用 Tkinter 提供的接口就能夠。app
編寫 「Hello World」,此次使用 Tkinter 模塊完成。函數
先導入 Tkinter 庫工具
Python 3.x 版本,Tkinter 庫已經更改成 tkinter,導入命令以下:
from tkinter import *
或者oop
import tkinter
從 Frame
派生一個 Application
類,這是全部 Widget 的父容器:佈局
class Application(Frame): '''由 Frame 派生 Application ''' def __init__(self, master=None): Frame.__init__(self, master) self.pack() self.create_widgets() def create_widgets(self): self.hello_label = Label(self, text='Hello, world!') self.hello_label.pack() self.quit_button = Button(self, text='Quit', command=self.quit) self.quit_button.pack()
在 GUI 中,Button、Label、Entry 等,都是一個 Widget。Frame 則是能夠容納其餘 Widget 的 Widget。ui
pack()
方式把 Widget 加入父容器中,並實現佈局。pack()
是最簡單的佈局, grid()
網格佈局能夠實現更復雜的佈局。
在 create_widgets()
方法中,建立一個 Label
和 Button
,當 Button 被點擊時,觸發 self.quit()
使程序退出。
而後,實例化 Application
,並啓動消息循環:
# 實例化 Application app = Application() # 設置窗口標題 app.master.title('Hello World') # 主消息循環 app.mainloop()
GUI 程序的主線程負責監聽來自操做系統的消息,並依次處理每一條消息。所以,若是消息處理很是耗時,就須要在新線程中處理。
運行上面程序的效果:
點擊 Quit
按鈕退出或者左上角的 x
結束程序
上面的例子是以直接輸出的形式,如今嘗試加入一個文本框,讓用戶能夠輸入文本,點擊按鈕能夠讀取輸入信息,並彈出消息對話框顯示輸入的信息。
from tkinter import * import tkinter.messagebox as messagebox class Application(Frame): def __init__(self, master=None): '''初始化函數 ''' Frame.__init__(self, master) self.pack() self.create_widgets() def create_widgets(self): '''建立部件 ''' self.name_input = Entry(self) self.name_input.pack() self.alert_button = Button(self, text='Hello', command=self.hello) self.alert_button.pack() def hello(self): '''接收用戶輸入,顯示信息 ''' name = self.name_input.get() or 'world' messagebox.showinfo('Message', 'Hello, {}'.format(name)) # 實例化 Application app = Application() # 設置窗口標題 app.master.title('Hello World') # 主消息循環 app.mainloop()
代碼運行流程,當用戶點擊按鈕,觸發 hello()
,經過 self.name_input.get()
得到用戶輸入的文本後,使用 messagebox.showinfo()
彈出消息對話框。
程序運行的效果以下:
這裏只是簡單的嘗試使用 Tkinter 模塊完成簡單的實例,Tkinter 模塊能完成的功能遠不止這些。詳細的信息能夠參考 TKDocs https://tkdocs.com/tutorial/index.html
以上就是本篇的主要內容。
歡迎關注微信公衆號《書所集錄》