Skip to main content
 首页 » 编程设计

python之拆分多个文件 tkinter 框架

2025年05月04日8soundcode

我看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。如何将这么多页面(框架)拆分成单独的文件?

请您参考如下方法:

您已经将 Controller 传递给 PageOne,因此这可以作为提升页面的机制。我的建议是使按名称而不是按类引用页面成为可能,然后为 Controller 提供一个接受名称并引发该页面的方法。这样您的页面就不必相互导入,从而实现更松散的耦合。

它看起来像这样:

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")) 
        ...