How To Create Tkinter Widgets Inside Parent Class From Sub Class
The first example creates the post titles in his parent which works(except it doesn't delete the old titles when I search new ones), but because imo it looks super messy I wanted t
Solution 1:
Below code has two classes, MainApp
to structure outermost frame of our app, and then SearchFrame
class that uses a method from MainApp
to create a label in its parent widget. In this case SearchFrame
's parent widget is MainApp
. You can comment out geometry manager to self.frame2
if you want to see that the label is in fact created inside the parent widget subclass MainApp
. Again, I doubt that this is good practice:
import tkinter as tk
root = tk.Tk()
class MainApp(tk.Frame):
def __init__(self, master):
super().__init__(master)
#a child frame of MainApp object
self.frame1 = tk.Frame(self)
tk.Label(self.frame1, text="This is MainApp frame1").pack()
self.frame1.grid(row=0, column=0, sticky="nsew")
#another child frame of MainApp object
self.frame2 = SearchFrame(self)
self.frame2.grid(row=0, column=1, sticky="nsew")
def create_labels(self, master):
return tk.Label(master, text="asd")
class SearchFrame(tk.Frame):
def __init__(self, master):
super().__init__(master)
self.label = tk.Label(self, text="this is SearchFrame")
self.label.pack()
master.label1 = MainApp.create_labels(self, master)
master.label1.grid()
mainAppObject = MainApp(root)
mainAppObject.pack()
root.mainloop()
Post a Comment for "How To Create Tkinter Widgets Inside Parent Class From Sub Class"