简体   繁体   English

无法从模块导入功能

[英]Cannot import a function from a module

Basically I have 3 modules that all communicate with eachother and import eachother's functions. 基本上,我有3个模块,它们彼此通信并导入彼此的功能。 I'm trying to import a function from my shigui.py module that creates a gui for the program. 我正在尝试从shigui.py模块导入一个为程序创建GUI的函数。 Now I have a function that gets the values of user entries in the gui and I want to pass them to the other module. 现在,我有一个函数可获取gui中用户条目的值,并将其传递给其他模块。 I'm trying to pass the function below: 我正在尝试通过以下功能:
def valueget(): keywords = kw.get() delay = dlay.get() category = catg.get()

All imports go fine, up until I try to import this function with 直到我尝试使用
from shigui import valueget to another module that would use the values. from shigui import valueget到另一个将使用这些值的模块。 In fact, I can't import any function to any module from this file. 实际上,我无法从此文件将任何功能导入任何模块。 Also I should add that they are in the same directory. 另外,我还应该添加它们在同一目录中。 I'm appreciative of any help on this matter. 我对此事有任何帮助。

Well, I am not entirely sure of what imports what, but here is what I can tell you. 好吧,我不能完全确定进口什么,但这是我能告诉你的。 Python can sometimes allow for circular dependencies. 蟒有时可以允许循环依赖。 However, it depends on what the layout of your dependencies is. 但是,这取决于依赖项的布局。 First and foremost, I would say see if there is any way you can avoid this happening (restructuring your code, etc.). 首先,我要说的是看看是否有任何方法可以避免这种情况发生(重组代码等)。 If it is unavoidable then there is one thing you can try. 如果不可避免,那么您可以尝试一件事。 When Python imports modules, it does so in order of code execution. 当Python导入模块时,它按代码执行的顺序进行。 This means that if you have a definition before an import, you can sometimes access the definition in the first module by importing that first module in the second module. 这意味着,如果在导入之前具有定义,则有时可以通过将第二个模块中的第一个模块导入来访问第一个模块中的定义。 Let me give an example. 让我举个例子吧。 Consider you have two modules, A and B. 考虑您有两个模块,A和B。

A: A:

def someFunc():
    # use B's functionality from before B's import of A
    pass

import B

B: B:

def otherFunc():
    # use A's functionality from before A's import of B
    pass

import A

In a situation like that, Python will allow this. 在这种情况下,Python将允许这样做。 However, everything after the imports is not always fair game so be careful. 但是,导入后的所有内容并不总是公平的游戏,因此请小心。 You can read up on Python's module system more if you want to know why this works. 如果您想知道为什么它可以工作,可以进一步阅读Python的模块系统。

Helpful, but not complete link: https://docs.python.org/3/tutorial/modules.html 有用但不完整的链接: https : //docs.python.org/3/tutorial/modules.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM