我正在尝试使用更干净的格式创建一个Tkinter应用程序,灵感来自Bryan Oakley的建议。
import tkinter as tk
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
# Set start-up screen width and height
screen_width = self.parent.winfo_screenwidth()
screen_height = self.parent.winfo_screenheight()
self.parent.geometry(f"{screen_width}x{screen_height}")
# Adding Header
self.header = Header(self)
self.header.pack(side="top", fill="x")
class Header(tk.Frame):
def __init__(self, parent):
tk.Frame(parent, height=50, bg="#000000")
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()
然而,当运行这段代码时,我得到了这个错误:
AttributeError: 'Header' object has no attribute 'tk'
我做错了什么?
您的Header
类没有正确继承tk.Frame
。您需要确保调用基类的__init__
方法,就像您在MainApplication
中所做的那样。
class Header(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
...
tk。在Header
类中没有影响,因为帧没有用您继承的类(tk.Frame)初始化。因此,当你使用self.header.pack(side="top", fill="x")
时,你会得到错误。您可以使用下面的方法创建一个框架对象并将其放在init方法中。或者你可以在Header
类中添加一个方法,它将返回frame对象,因此你可以使用pack将它放在MainApplication
类中
import tkinter as tk
class MainApplication(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
# Set start-up screen width and height
screen_width = self.parent.winfo_screenwidth()
screen_height = self.parent.winfo_screenheight()
self.parent.geometry(f"{screen_width}x{screen_height}")
Header(self.parent)
class Header(object):
def __init__(self, parent):
self.parent = parent
self.frame = tk.Frame(self.parent, height=50, bg="#000000")
self.frame.pack(side="top", fill="x")
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).pack(side="top", fill="both", expand=True)
root.mainloop()