我正在嘗試使用 Bryan Oakley 在這篇文章中的建議的靈感,使用更清晰的格式創建一個 Tkinter 應用程式。
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'
我究竟做錯了什么?
uj5u.com熱心網友回復:
您的Header類沒有正確繼承自tk.Frame. 您需要確保__init__基類的方法像您在MainApplication.
class Header(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
...
uj5u.com熱心網友回復:
類中的tk.FrameHeader沒有影響,因為框架沒有使用您繼承的類 (tk.Frame) 進行初始化。因此,當您使用時, self.header.pack(side="top", fill="x")您會收到錯誤。您可以使用以下方法創建一個框架物件并將其放置在 init 方法中。或者您可以在Header類中再添加一個方法,該方法將回傳框架物件,從而您可以在MainApplication類中使用 pack 放置它
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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/323750.html
上一篇:Tkinter增量計數器
