正如您在代码中看到的那样,在MainWindow上它应该显示一个蓝色和绿色的框,一个在另一个的ontop上,然后SecondMainWindow应该有一个红色和yollow框显示在另一个的ontop上。通过运行代码,您可以看到从login
窗口到MainWindow
所有框架都保持原样,因为它们只在MainWindow
和SecondMainWindow
上
但是,当您从MainWindow
转到SecondMainWindow
时,问题仍然存在,而MainWindow
这些名称与哪个窗口相混淆。我已将SecondMainWindow
和import tkinter as tk
class start(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.frame = login()
self.frame.grid()
def change(self, frame):
self.frame.grid_forget()
self.frame = frame()
self.frame.grid()
class login(tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.master.geometry('300x300')
self.master.configure(bg='orange')
button1 = tk.Button(self.master, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)
def ChangeFrame(self):
self.master.change(MainWindow)
class MainWindow (tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.master.geometry('300x300')
self.master.configure(bg='white')
self.master.grid_rowconfigure(0, weight=2)
self.master.grid_rowconfigure(1, weight=3)
self.master.grid_columnconfigure(0, weight=1)
Frame1 = tk.Frame(self.master, background='blue', bd=1, relief='sunken')
Frame1.grid(row=0,column=0,padx=10,pady=10,sticky='nsew')
Frame2 = tk.Frame(self.master, background='green', bd=1, relief='sunken')
Frame2.grid(row=1,column=0,padx=10,pady=10,sticky='nsew')
button1 = tk.Button(Frame1, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)
def ChangeFrame(self):
self.master.change(SecondMainWindow)
class SecondMainWindow (tk.Frame):
def __init__(self, master=None, **kwargs):
tk.Frame.__init__(self, master, **kwargs)
self.master.geometry('300x300')
self.master.configure(bg='grey')
self.master.grid_rowconfigure(0, weight=1)
self.master.grid_rowconfigure(1, weight=1)
self.master.grid_columnconfigure(0, weight=1)
self.master.grid_columnconfigure(1, weight=1)
Frame3 = tk.Frame(self.master, background='yellow', bd=1, relief='sunken')
Frame3.grid(row=1,column=1,padx=10,pady=10,sticky='nsew')
Frame4 = tk.Frame(self.master, background='red', bd=1, relief='sunken')
Frame4.grid(row=0,column=1,padx=10,pady=10,sticky='nsew')
button1 = tk.Button(Frame4, text='New Frame', command = self.ChangeFrame).grid(row=0,column=0)
def ChangeFrame(self):
self.master.change(MainWindow)
app = start()
app.mainloop()
的背景设置为不同的颜色,以进一步了解应显示哪个帧。
self
正如你在使用时所看到的,只是自我改变了布局,我将如何解决这个问题?
答案 0 :(得分:1)
您正在为'a
中的每个窗口放置小部件,但是您复制的代码是为了使每个窗口都是一个独立的对象而设计的。单个窗口中的所有小部件必须是该窗口的子级。
简而言之,而不是:
self.master
你应该这样做:
class SecondMainWindow (tk.Frame):
def __init__(self, master=None, **kwargs):
...
Frame3 = tk.Frame(self.master, ...)
Frame4 = tk.Frame(self.master, ...)
...
如果您希望每个窗口都将窗口小部件直接放在根窗口中,那么您没有理由创建从class SecondMainWindow (tk.Frame):
def __init__(self, master=None, **kwargs):
...
Frame3 = tk.Frame(self, ...)
Frame4 = tk.Frame(self, ...)
...
继承的类。