-1

filename p1.py

import tkinter as tk

def action():
    import p2
root=tk.Tk()
root.title('part1')
root.geometry('200x200+50+50')
btn=tk.Button(root,text='click me',command=action)
btn.pack()
root.mainloop()

filename p2.py

After closing this window, I want to reopen it on clicking the click me button but it does not open once I close this window.

import tkinter as tk
root=tk.Toplevel()
root.title('part2')
root.geometry('200x200+50+50')
lbl=tk.Label(root,text='Hello everybody \n I have problem',font=("times new roman",20,'bold'))
lbl.pack()

root.mainloop()
  • ***"closing this window, ... reopen ... clicking the `[click me]`"***: If you close the window your `Button` will be destroyed or also not shown anymore. – stovfl Feb 08 '20 at 09:49
  • @DaniyalAhmad ***"no `Tk()` in `p2.py`"***: Yes my bad, thanks for pointing this out. – stovfl Feb 08 '20 at 10:24
  • 1
    Read up on [Modules](https://docs.python.org/3/tutorial/modules.html#modules) and [Tkinter understanding mainloop](https://stackoverflow.com/questions/29158220/tkinter-understanding-mainloop) – stovfl Feb 08 '20 at 10:26
  • 1
    `import` statement will only load the module once. Therefore the main code in the module will be executed once. Put the code in `p2.py` in a function then import the function from the module and execute the function. – acw1668 Feb 08 '20 at 10:50

1 Answers1

0

Here's a solution for you:

Module_one:

import tkinter as tk


def action():
    import action_module
    action_module.page_two()


root = tk.Tk()
root.title('part1')
root.geometry('200x200+50+50')

btn = tk.Button(root, text='click me', command=action)
btn.pack()

root.mainloop()

action_module:

def page_two():
    import tkinter as tk

    root = tk.Toplevel()
    root.title('part2')
    root.geometry('200x200+50+50')

    lbl = tk.Label(root, text='Hello everybody \n I think the problem is fixed',
                   font=("times new roman", 20, 'bold'))
    lbl.pack()

    root.mainloop()

Just put the code in the second module inside a function. Then call it inside the first file's action function.

DaniyalAhmadSE
  • 807
  • 11
  • 20