0

Just a quick question. I have been using Tkinter in Python in order to create Windows. My code is a bit all over the place when it is one file... Is it possible to call a window that will be located in a different file?

For example, Window1.py opens a window, there is a button in that window that should initiate window 2, which is located in Window2.py. Does the code physically have to be in the same file for it to work together?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Miki Ameryk
  • 21
  • 1
  • 6

2 Answers2

0

The answer to this question is yes. To link two python files, use:

If you are in python 3, use exec(open(r"example").read())

If you are in python 2, use open(r"example")

-

Note: the python 2 example works both in python 2 and 3

-

They do not need to be in the same file, just simply use their location. e.g. if I had a program on my desktop, I would use

exec(open(r"C:/Users/MyName/Desktop/program").read())

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jake
  • 772
  • 2
  • 8
  • 18
  • I'm not sure why one would use this over `import` - maybe if the filename is unknown (but even then ...) - but with your one-liners it'll be impossible to close the file handle. Please use `with` or `try/finally` to close the file handles. – nitzel Nov 13 '19 at 17:31
0

Yes you can do it:

import os
#executing the python file within the first using this command>>
os.system("python fle_name.py)
Paul Roub
  • 36,322
  • 27
  • 84
  • 93