I am intended to make one class use another class as widget, for example: a Label A, within this will be Label B, but apparently no object can be used as an attribute
AttributeError: 'Label_A' object has no attribute 'parent'
code that I am trying to use:
import tkinter as tk
win = tk.Tk()
win.title("Test")
win.geometry("640x480")
class Label_A(tk.Label):
def __init__(self, parent):
# make a Label
def label_a():
self.label_a = tk.Label(self.parent, text="LABEL A", bg="red", fg="white", font=("Arial", 20), width=300, height=300)
self.label_a.place(x=0, y=0)
label_a()
class Label_B(tk.Label):
def __init__(self, parent):
# make a Label
def label_b():
self.label_b = tk.Label(self.parent, text="LABEL B", bg="blue", fg="white", font=("Arial", 20), width=200, height=200)
self.label_b.place(x=0, y=0)
label_b()
Label_B(Label_A(win))
win.mainloop()
CodePudding user response:
Try to use derived class of tkinter.Frame
, so it can be frame in frame.
import tkinter as tk
class Frame_A(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.place(x=0, y=0, width=300, height=200)
self.label_a = self.label()
def label(self):
label = tk.Label(self, text="LABEL A", bg="red", fg="white", font=("Arial", 20))
label.place(x=0, y=0, width=300, height=200)
return label
class Frame_B(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.place(x=0, y=0, width=200, height=100)
self.label_b = self.label()
def label(self):
label = tk.Label(self, text="LABEL B", bg="blue", fg="white", font=("Arial", 20))
label.place(x=0, y=0, width=200, height=100)
return label
win = tk.Tk()
win.title("Test")
win.geometry("400x300")
Frame_B(Frame_A(win))
win.mainloop()