0

Given the accepted answer to this question:

Using buttons in Tkinter to navigate to different pages of the application?

Is there a way to extend the Page class so that one can initialize an arbitrary amount of pages from MainView, instead of having to create a new class for every separate page?

Thanks!

warnbergg
  • 552
  • 4
  • 14
  • Why not make it a var or a lambda function? Just a suggestion. I don't mess with classes often so I don't know you can do that while initializing. –  Nov 29 '17 at 22:21
  • 2
    If you want identical Pages then you can just call them Page class several times. – Novel Nov 29 '17 at 22:22

1 Answers1

0

The whole point of that example was to show how you could switch between different pages. I don't quite see a point of having multiple identical pages.

That being said, there's nothing to prevent you from creating as many instances of a single page as you want. Here's a slight modification of the answer you linked to, which creates ten identical pages and lets you cycle between them:

import Tkinter as tk

class Page(tk.Frame):
    def __init__(self, title):
        tk.Frame.__init__(self, bd=1, relief="sunken")
        self.label = tk.Label(self, text=title)
        self.label.pack(side="top", fill="both", expand=True)

    def show(self):
        self.lift()

class MainView(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        buttonframe = tk.Frame(self)
        container = tk.Frame(self)

        buttonframe.pack(side="top", fill="x", expand=False)
        container.pack(side="top", fill="both", expand=True, padx=2, pady=2)

        next_button = tk.Button(buttonframe, text=" > ", command=self.next_page)
        prev_button = tk.Button(buttonframe, text=" < ", command=self.prev_page)
        prev_button.pack(side="left")
        next_button.pack(side="left")

        self.pages = []
        for i in range(10):
            page = Page(title="page %d" % i)
            page.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
            self.pages.append(page)

        self.pages[0].show()

    def next_page(self):
        # move the first page to the end of the list, 
        # then show the first page in the list
        page = self.pages.pop(0)
        self.pages.append(page)
        self.pages[0].show()

    def prev_page(self):
        # move the last page in the list to the front of the list,
        # then show the first page in the list.
        page = self.pages.pop(-1)
        self.pages.insert(0, page)
        self.pages[0].show()


if __name__ == "__main__":
    root = tk.Tk()
    main = MainView(root)
    main.pack(side="top", fill="both", expand=True)
    root.wm_geometry("400x400")
    root.mainloop()
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685