1. 程式人生 > >關於Python製作簡單的圖形介面GUI

關於Python製作簡單的圖形介面GUI

#簡單的圖形介面GUI(Graphical User Interface)
from tkinter import *
import tkinter.messagebox as messagebox
class Application(Frame):   #從Frame派生出Application類,它是所有widget的父容器
    def __init__(self,master = None):#master即是視窗管理器,用於管理視窗部件,如按鈕標籤等,頂級視窗master是None,即自己管理自己
        Frame.__init__(self,master)
        self.pack()#將widget加入到父容器中並實現佈局
        self.createWidgets()
    def createWidgets(self):
        self.helloLabel = Label(self,text = 'hi')#建立一個標籤顯示內容到視窗
        self.helloLabel.pack()
        self.quitButton = Button(self,text = 'Quit',command = self.quit)#建立一個Quit按鈕,實現點選即退出視窗
        self.quitButton.pack()
        self.input = Entry(self)#建立一個輸入框,以輸入內容
        self.input.pack()
        self.nameButton = Button(self,text = 'hello',command = self.hello)#建立一個hello按鈕,點選呼叫hello方法,實現輸出

        self.nameButton.pack()

    def hello(self):
        name = self.input.get()#獲取輸入的內容
        messagebox.showinfo('Message','hello,%s' %name)#顯示輸出
app = Application()
app.master.title("hello")#視窗標題

app.mainloop()#主訊息迴圈

輸出: