Home > Mobile >  Python Tkinter: Changing between frames dynamically
Python Tkinter: Changing between frames dynamically

Time:07-16

I'm new to python and decided to fiddle about with a bit of GIU and was wondering how can I switch between frames in a different file dynamically? I've tried adding command=Navigator.change_to_page(self, createMenuFrame) to a button but for some reason, it just combines the frames into one. Is the way I'm trying to do this doable or better to stick with a single main.py file?

enter image description here

I've structured my project in the following way:

enter image description here

main.py:

from tkinter import *
import views.viewMaker as viewMaker

root = Tk()

root.geometry("1200x700")
root.resizable(0, 0)

# Main Frame
mainFrame = Frame(root, bg="gray", width=1200, height=700)
mainFrame.pack()
mainFrame.pack_propagate(0)

viewMaker.ViewMaker.define_views(mainFrame)

root.mainloop()

views/viewMaker.py:

from tkinter import *
import commands.navigator as Navigator

class ViewMaker:
    def define_views(self):
        mainMenuFrame = Frame(self, bg="white", width=300, height=700) #Define Main Menu
        createMenuFrame = Frame(self, bg="white", width=300, height=700) #Define Creator Menu

        ViewMaker.populate_main_menu(mainMenuFrame, createMenuFrame) #Populate Main Menu
        ViewMaker.populate_create_menu(createMenuFrame) #Populate Create Menu

        mainMenuFrame.pack()
        mainMenuFrame.pack_propagate(0)

    def populate_main_menu(self, createMenuFrame): #Define Main Menu Design
        mainMenuTitle = Label(self, text="Title", bg="white", font=("Georgia", 16, "bold"))
        mainMenuTitle.pack(pady=25)

        generateButton = Button(self, text="Generate New", width=300, font=("Georgia", 12, "bold"))
        generateButton.pack(pady=5, side=TOP)

        createButton = Button(self, text="Create New", width=300, font=("Georgia", 12, "bold"), command=Navigator.change_to_page(self, createMenuFrame))
        createButton.pack(pady=5, side=TOP)

        quitButton = Button(self, text="Quit", width=300, font=("Georgia", 12, "bold"), command=self.master.master.destroy)
        quitButton.pack(pady=25, side=BOTTOM)

    def populate_create_menu(self): #Define Create Menu Design
        createMenuTitle = Label(self, text="Create New", bg="white", font=("Georgia", 16, "bold"))
        createMenuTitle.pack(pady=25)

commands/navigator.py:

from tkinter import *

def change_to_page(self, newPage):
    newPage.pack()
    newPage.pack_propagate()
    self.pack_forget()

CodePudding user response:

Note that command=Navigator.change_to_page(self, createMenuFrame) will execute Navigattor.change_to_page() immediately which shows the createMenuFrame.

Change it to command=lambda: Navigator.change_to_page(self, createMenuFrame) instead.

  • Related