Day-16: 圖形界面

  Python支持多種圖形界面,有:第三方庫有Tk、wxWidgets、Qt、GTK等。app

  Python自帶的庫是支持Tk的Tkinter,無需安裝任何安裝包,就能夠直接使用。函數

  在Python中使用函數調用Tkinter的接口,而後Tk會調用操做系統提供的本地GUI接口,完成最終的GUI。oop

  編寫一個簡單的GUI:佈局

from Tkinter import *

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()
app = Application()
# 設置窗口標題:
app.master.title('Hello World')
# 主消息循環:
app.mainloop()

  在GUI中,每個按鈕、標籤、輸入框都是一個Widget。Frame是最大的Widget,它能夠容納其餘的Widget。學習

  pack()方法是將已經建立好的Widget添加到父容器中,它是最簡單的佈局,grid()能夠實現相對複雜的佈局。ui

  在creatWidgets()方法中,建立的Button被點擊時,觸發內部的命令self.quit(),使程序退出。spa

  還能夠增長輸入文本的文本框:操作系統

from Tkinter import *
import tkMessageBox

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

  當用戶點擊按鈕時,觸發hello(),經過self.nameInput.get()得到用戶輸入的文本後,使用txMessageBox.showinfo()能夠彈出消息對話框。3d

 注:本文爲學習廖雪峯Python入門整理後的筆記code

相關文章
相關標籤/搜索