Home > Article > Backend Development > Python sharing examples of three inheritance methods for classes in the tkinter module
This article mainly introduces the three methods of class inheritance in the Python tkinter module. It analyzes the implementation methods and related precautions of the three inheritance methods in combination with examples. Friends in need can refer to this article
The example describes three ways of class inheritance in the Python tkinter module. Share it with everyone for your reference, the details are as follows:
There are three ways of tkinter class inheritance.
Remind us to pay attention to the operation methods of these inheritances
1. Inherit object
1. Shop tk .Frame to parent:
Description:
self.rootframe = tk.Frame(parent)<br>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. Use root directly
Instructions:
self.root = parent<br>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()
2. Inherit 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()
3. Inherit tk.Frame##There are two situations
1 .With 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() # 也可以这样
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()
The above is the detailed content of Python sharing examples of three inheritance methods for classes in the tkinter module. For more information, please follow other related articles on the PHP Chinese website!