As mentioned by Kevin, the import
statement only imports once. The easy solution would be to replace import page2
with os.system("python page2.py")
. But that would generate a new Python process each time you switch pages...
Instead, you could define each page of your app as a class, according to the structure shown here, and just save them in different files.
page1.py
import tkinter as tk
class Page1(tk.Frame):
def __init__(self, controller):
tk.Frame.__init__(self, controller)
tk.Label(self, text="Hi I am page 1").pack()
tk.Button(self, text="Page 2",
command=lambda:controller.show_page("Page2")).pack()
page2.py
import tkinter as tk
class Page2(tk.Frame):
def __init__(self, controller):
tk.Frame.__init__(self, controller)
tk.Label(self, text="Hi I am page 2").pack()
tk.Button(self, text="Page 1",
command=lambda:controller.show_page("Page1")).pack()
the controller file:
import tkinter as tk
from page1 import Page1
from page2 import Page2
class App(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.pages = {}
# Create 2 overlapping pages
for P in [Page1, Page2]:
page = P(self)
page.grid(row=0, column=0, sticky="nsew")
self.pages[P.__name__] = page
self.show_page("Page1")
def show_page(self, frameName):
self.pages[frameName].lift()
# Launch the app
app = App()
app.mainloop()