我看here。我可以将页面(框架)拆分为两个文件。例如,这是我的第一个文件:main.py
from Tkinter import *
from halsatu import *
class Biasa(Tk):
def __init__(self, *args, **kwargs):
Tk.__init__(self, *args, **kwargs)
container = Frame(self)
container.pack(expand=True)
container.grid_rowconfigure(0, weight=1)
container.grid_columnconfigure(0, weight=1)
self.frames = {}
for F in (StartPage, PageOne, PageTwo):
frame = F(container, self)
frame.grid(row=0, column=0, sticky='news')
self.frames[F] = frame
self.show_frame(StartPage)
def show_frame(self, c):
frame = self.frames[c]
frame.tkraise()
class StartPage(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
label = Label(self, text='Ini halaman Awal')
label.pack()
button = Button(self, text='ke Halaman 1',
command=lambda: controller.show_frame(PageOne))
button.pack()
button2 = Button(self, text='ke Hal. 2',
command=lambda: controller.show_frame(PageTwo))
button2.pack()
class PageTwo(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
label = Label(self, text='Sekarang \nIni halaman Dua lho..')
label.pack()
button = Button(self, text='ke Halaman 1',
command=lambda: controller.show_frame(PageOne))
button.pack()
button2 = Button(self, text='ke Hal. Awal',
command=lambda: controller.show_frame(StartPage))
button2.pack()
if __name__ == '__main__':
app = Biasa()
app.mainloop()
然后这是我的halsatu.py:
from Tkinter import *
class PageOne(Frame):
def __init__(self, parent, controller):
Frame.__init__(self, parent)
label = Label(self, text='Kalau yang Ini halaman Satuuuuuuuuuuuuuuuuuu')
label.pack()
button = Button(self, text='ke Halaman Awal',
command=lambda: controller.show_frame(StartPage))
button.pack()
button2 = Button(self, text='ke Hal. 2',
command=lambda: controller.show_frame(PageTwo))
button2.pack()
该代码可以运行。但是当我转到pageone时,我无法再次返回StartPage。如何将这么多页面(框架)拆分成单独的文件?
答案 0 :(得分:1)
您已经将控制器传递给PageOne
,因此这可以是提升页面的机制。我的建议是,可以按名称而不是按类引用页面,然后为控制器提供一个接受名称并引发该页面的方法。这样,您的页面就不必相互导入,从而实现更松散的耦合。
它看起来像这样:
class Biasa(Tk):
...
def show_page(self, page_name):
for F in self.frames:
if F.__name__ == page_name:
self.show_frame(F)
return
class PageOne(Frame):
def __init__(self, parent, controller):
...
button = Button(..., command=lambda: controller.show_page("StartPage"))
...