1
from tkinter import *

def page2():
    root1.destroy()
    import page2

root1 = Tk()
root1.geometry("300x150+177+180")
Label(root1, text="Hi I am page 1").pack()
Button(root1, text="Page 2", command=page2).pack()
root1.mainloop()

and page 2 :

from tkinter import *

def page1():
    root2.destroy()
    import page1

root2 = Tk()
root2.geometry("300x150+177+180")
Label(root2, text="Hi I am page 2").pack()
Button(root2, text="Page 1", command=page1).pack()
root2.mainloop()

The program works fine, but when you use the button twice, the program stops.

Walid Bousseta
  • 1,329
  • 2
  • 18
  • 33
  • That's the whole program? where is your entry point?? – Dayan May 23 '17 at 15:44
  • 1
    If I understand the module system properly, then `import page1` will do nothing, because page1.py already executed. (Posting this as a comment and not an answer because I haven't thought of a reply to the follow-up question, "so how should I rewrite my program so that it does what I want?") – Kevin May 23 '17 at 15:44
  • this is simply not the correct way to use tkinter. What are you trying to accomplish? – Bryan Oakley May 23 '17 at 16:25
  • The application I implement is divided into several files and I need to get them with one execution – Walid Bousseta May 23 '17 at 18:23

1 Answers1

0

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()
Josselin
  • 2,593
  • 2
  • 22
  • 35