我打算讓一個類使用另一個類作為小部件,例如:標簽 A,其中將是標簽 B,但顯然沒有物件可以用作屬性
AttributeError: 'Label_A' object has no attribute 'parent'
我正在嘗試使用的代碼:
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()
uj5u.com熱心網友回復:
嘗試使用 的派生類tkinter.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()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/386302.html
