Question

I'm trying to build a little app that lets you switch between to pages. This is what I got so far:

import tkinter 
from tkinter import ttk

def main():
    root=tkinter.Tk()
    root.title("Control")
    first_page = FirstWindow(root)
    root.mainloop()


def change_to_secondwindow():
    first_page.grid_forget()
    second_page = SecondWindow(root)


class FirstWindow(ttk.Frame):
    def __init__(self,root):
        ttk.Frame.__init__(self,root)
        self.grid()
        self.widgets1_create()

    def widgets1_create(self):
        self.b1 = ttk.Button(self, text="First Page", command=change_to_secondwindow)
        self.b1.grid()



class SecondWindow(ttk.Frame):
    def __init__(self,root):
        ttk.Frame.__init__(self,root)
        self.grid()
        self.widgets2_create()

    def widgets2_create(self):
        self.b2 = ttk.Button(self, text="Second Page")
        self.b2.grid()


main()

Now if I click on the button "First Page" to change to the second page I'm getting an error. It says that global name first_page is not defined. What's my mistake? Is there any better way to control changing windows with Tkinter?

Thank you for your help!

Was it helpful?

Solution

first_page is a local variable of main(), but you try to use it as a global variable in change_to_secondwindow(). Instead of this function, a common Python idiom is to put this code inside an if block where you check if the module is the main program:

# remove the call to main()

if __name__ == '__main__':
    root=Tkinter.Tk()
    root.title("Control")
    first_page = FirstWindow(root)
    root.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top