James P.
James P.

Reputation: 41

Tkinter: a second script open a new window not requested?

example1.py:

from tkinter import *
root = Tk()

filename = 'james'

Lbl = Label(root,text="ciao")
Lbl.pack()

root.mainloop()

example2.py:

from example1 import filename
print(filename)

Why python open tkinter window if I run only example2.py? It is necessary for me that filename is in the example1.py and called from example2.py. I called only filename variable and not a tkinter window in example2.

Upvotes: 0

Views: 86

Answers (2)

LiftUpStack
LiftUpStack

Reputation: 58

This is because the standard rules of Python
yup! Python automatically excecutes the Python file which you imported.In Your Case its example1 file.

To prevent This Use this instance:

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

in your file see

Edit:

And the rest problem is that, You cannot directly import a variable from a file.

You Will have to store it in an function like:
yourFileName

So your final code will be

example1.py

from tkinter import *
root = Tk()

filename = 'james'

Lbl = Label(root,text="ciao")
Lbl.pack()

def filenamefunc():
    return filename

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

And your example2.py will be

from example1 import filenamefunc
print(filenamefunc)

Thank-you

Upvotes: 1

Chansub Kim
Chansub Kim

Reputation: 48

First, I don't know how to solve your problem. but I know what you want to know.

I understand you have two python file ('example 1' and 'example 2'). And you want to import 'filename' from 'example 1'. But Tkinter is worked and you want to know why. right?

The import function is not pick-up tool.

*** That's mean you can't get the 'filename' without other data-processing.***

When you call the import file 'example1', python is run the 'example1' code from beginning to end and get the filename. It's faster to try than to explain.

from tkinter import *
filename = 'james'
print(' before ')
root = Tk()
Lbl = Label(root,text="ciao")
Lbl.pack()
root.mainloop()
print(' after ')

Fix your code like this and run 'example 2'. First,You can see 'before' text in your terminal. And tkinter will be ran and then when you close the tkinter, you can see 'after' text and work your code print(filename)

example1[filename is saved 'james' >> print 'before' >> run the tkinter mainloop >> print 'after'] >> example2[get filename from example1 >> filename is 'james' >> print(filename)]

Anyway, It's the answer about 'why' tkinter is run.

Upvotes: 0

Related Questions