為Python程式添加圖形化介面的教程

來源:互聯網
上載者:User
Python支援多種圖形介面的第三方庫,包括:

  • Tk
  • wxWidgets
  • Qt
  • GTK

等等。

但是Python內建的庫是支援Tk的Tkinter,使用Tkinter,無需安裝任何包,就可以直接使用。本章簡單介紹如何使用Tkinter進行GUI編程。
Tkinter

我們來梳理一下概念:

  • 我們編寫的Python代碼會調用內建的Tkinter,Tkinter封裝了訪問Tk的介面;
  • Tk是一個圖形庫,支援多個作業系統,使用Tcl語言開發;
  • Tk會叫用作業系統提供的本地GUI介面,完成最終的GUI。

所以,我們的代碼只需要調用Tkinter提供的介面就可以了。
第一個GUI程式

使用Tkinter十分簡單,我們來編寫一個GUI版本的“Hello, world!”。

第一步是匯入Tkinter包的所有內容:

from Tkinter import *

第二步是從Frame派生一個Application類,這是所有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中,每個Button、Label、輸入框等,都是一個Widget。Frame則是可以容納其他Widget的Widget,所有的Widget組合起來就是一棵樹。

pack()方法把Widget加入到父容器中,並實現布局。pack()是最簡單的布局,grid()可以實現更複雜的布局。

在createWidgets()方法中,我們建立一個Label和一個Button,當Button被點擊時,觸發self.quit()使程式退出。

第三步,執行個體化Application,並啟動訊息迴圈:

app = Application()# 設定視窗標題:app.master.title('Hello World')# 主訊息迴圈:app.mainloop()

GUI程式的主線程負責監聽來自作業系統的訊息,並依次處理每一條訊息。因此,如果訊息處理非常耗時,就需要在新線程中處理。

運行這個GUI程式,可以看到下面的視窗:

點擊“Quit”按鈕或者視窗的“x”結束程式。
輸入文本

我們再對這個GUI程式改進一下,加入一個文字框,讓使用者可以輸入文本,然後點按鈕後,彈出訊息對話方塊。

from Tkinter import *import tkMessageBoxclass 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'    tkMessageBox.showinfo('Message', 'Hello, %s' % name)

當使用者點擊按鈕時,觸發hello(),通過self.nameInput.get()獲得使用者輸入的文本後,使用tkMessageBox.showinfo()可以彈出訊息對話方塊。

程式運行結果如下:

小結

Python內建的Tkinter可以滿足基本的GUI程式的要求,如果是非常複雜的GUI程式,建議用作業系統原生支援的語言和庫來編寫。

源碼參考:https://github.com/michaelliao/learn-python/tree/master/gui

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.