Sh23
Sh23

Reputation: 67

Problems with import stament when using tkinter

I have the following problem: I want to import a variable from one file into another. But when the file from which I import has a tkinter window, it opens the entire window instead of just importing the variable. How do I solve this ?

Code from file1

from tkinter import *

root = Tk()

A = "This is "
B = "a test."
C = A+B
D = Label(root, text=C, font="Arial 20 bold")
D.pack()


root.mainloop()

Code from file2

from file1 import C
print(C)

Upvotes: 3

Views: 76

Answers (1)

yeeshue99
yeeshue99

Reputation: 248

This happens because when you import python files, you are essentially running the entire file to get a reference. When file1 runs in its entirety, the entire file is interpreted and ran. This includes the last line, root.mainloop()

What you want to use is the best practice of having a check for if the current file is the main file. This will prevent it from running certain lines of code if it is not the current, main program.

You're looking for something like this:

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

Upvotes: 3

Related Questions