0

Here some simple, working code (it's from StackOverflow via sentdex):

import tkinter as tk

LARGE_FONT = ("Verdana", 12)

class App(tk.Tk):
    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)
        tk.Tk.title(self, "This is App")

        container = tk.Frame(self)

        container.pack(side=tk.TOP, fill=tk.BOTH, expand=True)

        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, PageOne):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky=tk.NSEW)

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):
    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="StartPage", font=LARGE_FONT)
        label.pack(padx=10, pady=10)

        button = tk.Button(self, text="Visit Page 1",
                            command=lambda: controller.show_frame(PageOne))
        button.pack()

class PageOne(tk.Frame):
    def __init__(self, parent, controller):

        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="Page One!", font=LARGE_FONT)
        label.pack(padx=10, pady=10)

        button = tk.Button(self, text="Back to Home",
                            command=lambda: controller.show_frame(StartPage))
        button.pack()

app = App()
app.mainloop()

Now I am trying to put PageOne (and each additional page/pagelogik) into a separate file and import it as module, e.g. import <modulename> as <prefix>.

This works up to the point, when one does click on the Button on "Page One!" - but then it fails, because StartPage is unknown in this file.

So I just couldn't figure out by myself how to pass a reference of StartPage to PageOne. I guess a circular import StartPage within the file of PageOne would be a stupid mess.

Community
  • 1
  • 1
Chrugel
  • 883
  • 2
  • 11
  • 19

1 Answers1

2

The solution is pretty simple: make show_frame accept the name of a page as a string. Then, only the app class needs to import every page. It can then find the instance of the class based on the class name.

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
  • Well now I just added an `eval()` around the `cont`, which now is provided as String. It does work, so thank you very much! Maybe `eval()` is considered an unsafe way for this? – Chrugel Dec 11 '15 at 13:08
  • 1
    @Chrugel: yes, `eval()` is a poor choice. I've updated [the original answer](http://stackoverflow.com/a/7557028/7432) with a solution. – Bryan Oakley Dec 11 '15 at 13:23