【问题标题】:Why do I receive an AttributeError even though import, spelling and file location is correct?为什么即使导入、拼写和文件位置正确,我也会收到 AttributeError?
【发布时间】:2019-04-18 08:05:02
【问题描述】:
  1. 我正在使用 PyCharm
  2. 所有文件都在目录'venv'中

    • venv
    • NoteFunction.py
    • NoteMainApp.py
    • ...

我将代码分成五个单独的文件。一个“主”文件,收集所有其他文件并最终创建 GUI。文件的前缀是“注意”,后面有适当的描述。

我现在的问题是将“NoteTopMenu”导入主文件“NoteMainApp”。 代码是:

import NoteStatusbar as SB
import NoteTopMenu as TM
import NoteWidgets as NW
import tkinter as tk


class MainApp(tk.Frame):

    def __init__(self, parent):

        tk.Frame.__init__(self,parent)
        super().__init__(parent)
        self.topbar = TM.TopMenu(parent)
        self.widget = NW.FrontFrames(parent)
        self.statusbar = SB.StatusBar(parent)


root = tk.Tk()
MainApp(root).pack(side="top", fill="both")

root.mainloop()

我收到错误消息:

Traceback (most recent call last):
  File "C:/Users/PycharmProjects/MindNotez/NoteMainApp.py", line 2, in <module>
    import NoteTopMenu as TM
  File "C:\Users\PycharmProjects\MindNotez\NoteTopMenu.py", line 2, in <module>
    import NoteMainApp as Main
  File "C:\Users\PycharmProjects\MindNotez\NoteMainApp.py", line 29, in <module>
    MainApp(root).pack(side="top", fill="both")
  File "C:\Users\PycharmProjects\MindNotez\NoteMainApp.py", line 13, in __init__
    self.topbar = TM.TopMenu(parent)

AttributeError:模块“NoteTopMenu”没有属性“TopMenu”

NoteTopMenu中的代码是:

import NoteMainApp as Main
import NoteWidgets as NW
import tkinter as tk


class TopMenu(NW.FrontFrames):
    """Class creating the top menu bar."""
    def __init__(self, master):
        super().__init__(master)
        # *******Top-Navigation Bar (tnb)**********
        tnb = tk.Menu(master)
        Main.root.config(menu=tnb)
        ....

如果我在主文件中将 NoteTopMenu 注释掉,则代码可以正常运行。我检查了我的拼写,但 PyCharm 还为我提供了代码补全功能。因此,PyCharm 发现文件、模块、我的类和其他模块被导入没有问题。 您知道为什么找不到或无法导入文件/模块吗?

完整代码在 GitHub 上:MindNotez

非常感谢您的帮助!

【问题讨论】:

  • 顺便说一句,恭喜您提出了一个非常明确的问题,并提供了完整的所需信息。

标签: python python-3.x attributeerror


【解决方案1】:

您调用 NoteMainApp.py 导入 NoteTopMenu.py 导入 NoteMainApp.py 继续重新导入 NoteTopMenu.py(因为导入已经开始)。 NoteMainApp.py 的导入然后继续解析文件的其余部分。此时模块NoteTopMenu 已定义,但它没有任何属性(因为您还没有来得及定义它们)......因此出现错误。

我建议NoteTopMenu.py 不应该导入NoteMainApp.py (如果有两个文件都需要的任何位,它们应该移动到另一个可以导入的文件中)

【讨论】:

  • 非常感谢您的回答。我会试一试,然后回复大家。
  • 这称为循环依赖循环导入。在 python 中这通常是一个坏主意,因为它往往会导致像这里显示的问题。如果您觉得有必要这样做,则表明您组织代码的方式存在设计问题。这里有一篇很好的博客文章stackabuse.com/python-circular-imports
  • 非常感谢大家。您的回答解释了我遇到的问题。
猜你喜欢
  • 2022-06-10
  • 2020-10-25
  • 2021-07-17
  • 2017-11-18
  • 2016-01-24
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 2022-08-20
相关资源
最近更新 更多