1. 程式人生 > >Python學習之旅(三十一)

Python學習之旅(三十一)

Python基礎知識(30):圖形介面(Ⅰ)

Python支援多種圖形介面的第三方庫:Tk、wxWidgets、Qt、GTK等等

Tkinter可以滿足基本的GUI程式的要求,此次以用Tkinter為例進行GUI程式設計

一、編寫一個GUI版本的“Hello, world!”

本人使用的軟體是pycharm

#導包
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.qutiButton = Button(self, text='Quit', command=self.quit) self.qutiButton.pack() #例項化Application,並啟動訊息迴圈
app = Application() #設定視窗標題 app.master.title('Hello, world!') #主訊息迴圈 app.mainloop()

在GUI中,每個Button、Label、輸入框等,都是一個Widget。

Frame則是可以容納其他Widget的Widget,所有的Widget組合起來就是一棵樹。

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

createWidgets()方法中,我們建立一個Label和一個Button,當Button被點選時,觸發self.quit()

使程式退出

點選“Quit”按鈕或者視窗的“x”結束程式

二、新增文字輸入

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

from tkinter import *
import tkinter.messagebox as messagebox

class 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'
        messagebox.showinfo('Message', 'Hello, %s' % name)

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

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