1. 程式人生 > 實用技巧 >Python19-06_GUI程式設計-----經典面向物件寫法

Python19-06_GUI程式設計-----經典面向物件寫法

經典面向物件寫法

本節程式也是GUI應用程式的一個主要結構, 採用了面向物件的方式, 更加合理的組織程式碼

通過類Application組織整個GUI程式, 類Application繼承了父類的特性, 通過__init__()初始化視窗中的物件, 通過createWidgets()方法建立視窗中的物件

Frame框架是一個tkinter元件, 表示一個矩形區域. Frame通常作為容器使用, 可以放置其他元件, 從而實現複雜的佈局

Practice: 測試一個經典的GUI程式的寫法, 使用面向物件的方式

 1 # coding:utf-8
 2 from tkinter import
* 3 from tkinter import messagebox 4 5 6 class Application(Frame): 7 """一個經典的GUI程式類寫法""" 8 def __init__(self, master=None): 9 super().__init__(master) # super代表的是父類的定義,而不是父類的物件 10 self.master = master 11 self.pack() 12 13 self.createWidget()
14 15 def createWidget(self): 16 """建立元件""" 17 self.btn01 = Button(self) 18 self.btn01['text'] = "點選送花" 19 self.btn01.pack() 20 self.btn01["command"] = self.songhua 21 self.btnQuit = Button(self, text='退出', command=self.destroy) 22 self.btnQuit.pack()
23 24 def songhua(self): 25 messagebox.showinfo('送花', '送你99朵玫瑰花') 26 27 28 root = Tk() 29 root.geometry("400x100+200+300") 30 root.title('測試') 31 app = Application(master=root) 32 root.mainloop()