Skip to content Skip to sidebar Skip to footer

Python Circular Dependencies, Unable To Link Variable To Other File

I am working on a program that allows me to directly edit a word document through a tkinter application. I am trying to link the tkinter input from my gui file to my main file so t

Solution 1:

The import mechanism is designed to allow circular imports. But one must remember the following:

  1. The name of the main module created from the startup script is __main__, rather than as its filename minus .py. Any other file importing the startup script must import __main__, not import filename. (Otherwise, a second module based on the startup script will be created with its normal name.)

  2. Execution of the code in a module is paused at each import. The order of initial imports is important as the last module in the chain is the first to be run to completion. Each object within modules must be available when the reference is executed. References within function definitions are not executed during the import process.

Applying the above to your pair, I assume that gui.py is the startup script. Python will immediate create an empty module object as the value of sys.modules['__main__']. Somain.pyshould importgui.pywithimport main as gui(the name change is just for convenience). Within the function definition, you should be able to usegui.entrywithout problem since there will be no attempt to lookupgui.entryuntil the function is called. I suggest addingentry = gui.entryas the first line of the function and usingentry` in the two places needed.

The following pair of files run as desired when tem2.py is run.

# tem2.pyimport tem3
a = 3print(tem3.f())

# tem3.pyimport __main__ as tem2
deff():
  return tem2.a

Solution 2:

Move the definition of entry into a third file and import it in both files.

Solution 3:

You can pass the entry to WebsiteChange:

def WebsiteChange(entry):
    website = entry.get()

submit = Button(master, text="Submit", 
    command=lambda e=entry: main.WebsiteChange(e))

Post a Comment for "Python Circular Dependencies, Unable To Link Variable To Other File"