Python tkinter模組中類繼承的三種方式分析,pythontkinter
本文執行個體講述了Python tkinter模組中類繼承的三種方式。分享給大家供大家參考,具體如下:
tkinter class繼承有三種方式。
提醒注意這幾種繼承的運行方式
一、繼承 object
1.鋪tk.Frame給parent:
說明:
self.rootframe = tk.Frame(parent)
tk.Label(self.rootframe)
import tkinter as tkclass MyApp(object): def __init__(self, parent): self.rootframe = tk.Frame(parent) self.rootframe.pack() self.setupUI() def setupUI(self): tk.Label(self.rootframe, text='標籤').pack()if __name__ == '__main__': root = tk.Tk() MyApp(root) # 注意這句 root.mainloop()
2.直接使用root
說明:
self.root = parent
tk.Label(self.root)
import tkinter as tkclass MyApp(object): def __init__(self, parent, **kwargs): self.root = parent self.root.config(**kwargs) self.setupUI() def setupUI(self): tk.Label(self.root, text = '標籤').pack()if __name__ == '__main__': root = tk.Tk() app = test(root) root.mainloop()
二、繼承 tk.Tk
import tkinter as tkclass MyApp(tk.Tk): def __init__(self): super().__init__() self.setupUI() def setupUI(self): tk.Label(self, text='標籤').pack()if __name__ == '__main__': MyApp().mainloop()
三、繼承 tk.Frame
分兩種情況
1.有parent
import tkinter as tkclass MyApp(tk.Frame): def __init__(self, parent=None): super().__init__(parent) self.pack() self.setupUI() def setupUI(self): tk.Label(self, text='標籤').pack()if __name__ == '__main__': MyApp(tk.Tk()).mainloop() #MyApp().mainloop() # 也可以這樣
注意: self.pack()
2.沒有parent
import tkinter as tkclass MyApp(tk.Frame): def __init__(self): super().__init__() self.pack() self.setupUI() def setupUI(self): tk.Label(self, text='標籤').pack()if __name__ == '__main__': MyApp().mainloop()