python

超轻量级php框架startmvc

Python tkinter模块中类继承的三种方式分析

更新时间:2020-05-05 20:30:01 作者:startmvc
本文实例讲述了Pythontkinter模块中类继承的三种方式。分享给大家供大家参考,具体如下:tk

本文实例讲述了Python tkinter模块中类继承的三种方式。分享给大家供大家参考,具体如下:

tkinter class继承有三种方式。

提醒注意这几种继承的运行方式

一、继承 object

1.铺tk.Frame给parent:

说明:

self.rootframe = tk.Frame(parent) tk.Label(self.rootframe)


import tkinter as tk
class 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 tk
class 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 tk
class 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 tk
class 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 tk
class 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()

Python tkinter模块 类继承