0

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!

user2304540
  • 101
  • 1
  • 2
  • 8
  • The error says that the global `first_page` is not defined. Can you show in your code where you think you're creating a global named `first_page`? – Bryan Oakley Apr 22 '13 at 11:10

1 Answers1

0

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()
A. Rodas
  • 20,171
  • 8
  • 62
  • 72
  • Okay it works, thank you! Now my final goal is a rather big GUI with eight diffrent windows. So it would really awesome if anybody could tell me how I can make it possible to move back to first page and how I can expand this if block – user2304540 Apr 22 '13 at 13:09