Python Circular dependencies, unable to link variable to other file

2024/10/15 1:23:50

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 that I can execute my docx functions. When I try to execute my code this way, it tells me that entry in entry.get() is not defined. When I try to import this from main, I receive a circular import error.

main.py

from docx import Document
from docx.shared import Inches
import os
os.chdir("\\Users\\insanepainz\Desktop")
doc = Document('TemplateTest.docx')
paragraphs = doc.paragraphsdef WebsiteChange():website = entry.get()print(website)master.quit()for paragraph in doc.paragraphs:if '^website' in paragraph.text:paragraph.text = gui.entryprint(paragraph.text)doc.save(doc)pass

gui.py

import main                                                                         
from tkinter import *                                                               
master = Tk()                                                                       #------------Web Entry Window                                                       
Label(master, text="Website Name: ").grid(row=0, sticky=W)                          entry = Entry(master)                                                               
entry.grid(row=0, column=1)                                                         # Connect the entry with the return button                                          
submit = Button(master, text="Submit", command=main.WebsiteChange)
submit.grid(row=1)      
# Centers the program window                                                        
master.eval('tk::PlaceWindow %s center' % master.winfo_pathname(master.winfo_id())) mainloop()                                                                          

I have been struggling to understand this concept for awhile. Circular errors are giving me a headache. Any help would be greatly appreciated.

Answer

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.py
import tem3
a = 3
print(tem3.f())# tem3.py
import __main__ as tem2
def f():return tem2.a
https://en.xdnf.cn/q/117886.html

Related Q&A

how to use xlrd module with python for abaqus

Im working on a script for abaqus where I have to import data from an excel file to put them into my script. I already downloaded the xlrd module and it work well on python interpreter (IDLE), but when…

Property in Python with @property.getter

I have an intresting behaviour for the following code:class MyClass:def __init__(self):self.abc = 10@propertydef age(self):return self.abc@age.getterdef age(self):return self.abc + 10@age.setterdef age…

Foreign Key Access

--------------------------------------------MODELS.PY-------------------------------------------- class Artist(models.Model):name = models.CharField("artist", max_length=50) #will display &…

ValueError: could not broadcast input array from shape (22500,3) into shape (1)

I relied on the code mentioned, here, but with minor edits. The version that I have is as follows:import numpy as np import _pickle as cPickle from PIL import Image import sys,ospixels = [] labels = []…

VGG 16/19 Slow Runtimes

When I try to get an output from the pre-trained VGG 16/19 models using Caffe with Python (both 2.7 and 3.5) its taking over 15 seconds on the net.forward() step (on my laptops CPU).I was wondering if …

Numpy vs built-in copy list

what is the difference below codesbuilt-in list code>>> a = [1,2,3,4] >>> b = a[1:3] >>> b[1] = 0 >>> a [1, 2, 3, 4] >>> b [2, 0]numpy array>>> c …

Scrapy returns only first result

Im trying to scrape data from gelbeseiten.de (yellow pages in germany)# -*- coding: utf-8 -*- import scrapyfrom scrapy.spiders import CrawlSpiderfrom scrapy.http import Requestfrom scrapy.selector impo…

Softlayer getAllBillingItems stopped working?

The following python script worked like a charm last month:Script:import SoftLayer client = SoftLayer.Client(username=someUser, api_key=someKey) LastInvoice = client[Account].getAllBillingItems() print…

Looking for a specific value in JSON file

I have a json file created by a function. The file is looks like this :{"images": [{"image": "/WATSON/VISUAL-REC/../IMAGES/OBAMA.jpg", "classifiers": [{"cla…

How to put many numpy files in one big numpy file without having memory error?

I follow this question Append multiple numpy files to one big numpy file in python in order to put many numpy files in one big file, the result is: import matplotlib.pyplot as plt import numpy as np i…