0

Suppose I have one GUI with a simple code as follows It has a button on it and when this is clicked I want to have another GUI to pop-up and then call the function from it. The problem is that when I run the first file, the GUI of the other one automatically pop-up. What should I do.

The code of the first file is as follows

from tkinter import *
import another

root = Tk()

button1 = Button(root, text = "Call" , command = another.abc)
button1.pack()

root.mainloop()

The code of second file another.py is as follows

from tkinter import *

root_Test2 = Tk()
root_Test2.geometry('450x450')

def abc():
     print("that's working")


root_Test2.mainloop()

Please suggest the solution that help me to open the second window when the button on the first one is clicked

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Zeryab Hassan Kiani
  • 467
  • 1
  • 7
  • 18
  • 1
    To import one .py file into another you need to structure it properly as a [module](https://docs.python.org/3/tutorial/modules.html) so that the code doesn't get run when you import it. – PM 2Ring Mar 22 '17 at 06:06
  • can you suggest the changes, I have to make in second file so that mainloop() of the second don't get called – Zeryab Hassan Kiani Mar 22 '17 at 06:12
  • If you've read that tutorial article I linked you to, you should be able to figure that out for yourself. It's not just the `mainloop` that shouldn't get run, the `root_Test2 = Tk()` and `root_Test2.geometry('450x450')` shouldn't get run either. Only the Tkinter import and the `abc` function definition can get executed. The other stuff _must_ be protected inside a `if __name__ == "__main__":` block. – PM 2Ring Mar 22 '17 at 06:41
  • So have a go at doing that, and if you _still_ can't figure it out, edit the code in your question to show your latest attempt. – PM 2Ring Mar 22 '17 at 06:43

1 Answers1

1

According to @PM 2Ring, You can change your second file's code to this:

from tkinter import *
if __name__ == '__main__':
    root_Test2 = Tk()
    root_Test2.geometry('450x450')

def abc():
     print("that's working")

if __name__ == '__main__':
    root_Test2.mainloop()

You can find further information about if __name__ == '__main__' here

Community
  • 1
  • 1
Mia
  • 2,466
  • 22
  • 38