Python / PySide ImportError

时间:2014-10-28 10:28:25

标签: python pyside

所以我最近开始学习python和工具包PySide但我遇到了一个我找不到解决方案的问题,这里是错误代码:

Traceback (most recent call last):
  File "C:\Users\Callum\workspace\Application\main.py", line 1, in <module>
    from ui.window import Window
  File "C:\Users\Callum\workspace\Application\ui\window.py", line 4, in <module>
    from ui.menubar import MenuBar
  File "C:\Users\Callum\workspace\Application\ui\menubar.py", line 3, in <module>
    from ui.window import Window
ImportError: cannot import name 'Window'

以下是代码:

main.py:

from ui.window import Window

wind = Window()
wind.Create()

window.py:

import sys
from PySide.QtCore import *
from PySide.QtGui import *
from ui.menubar import MenuBar

class Window:

    title = "Callum"
    minWidth = 980
    minHeight = 640
    app = None
    win = None

    def Create(self):

        self.app = QApplication(sys.argv)
        self.win = QMainWindow()

        self.win.setWindowTitle(self.title)
        self.win.setMinimumSize(self.minWidth, self.minHeight)

        mB = MenuBar()
        mB.Create()

        self.win.show()

        sys.exit(self.app.exec_())

menubar.py:

from PySide.QtCore import *
from PySide.QtGui import *
from ui.window import Window

class MenuBar:

    def Create(self):

        wind = Window()
        menu = wind.menuBar()

        fileMenu = menu.addMenu("File")
        fileMenu.addAction("Exit", exit)

1 个答案:

答案 0 :(得分:0)

如果仔细查看追溯,您会看到:

  1. main.py 导入ui.window
  2. 然后:

    1. window.py 导入ui.menubar
    2. 然后:

      1. menubar.py 导入ui.window
      2. 现在我们进入无限循环的导入,window导入menubar导入window导入menubar ...等等。除此之外当然,python通过引发错误来防止这种情况发生。

        但是,应用程序的结构存在其他问题。特别是,Menubar.Create方法创建了Window的新实例,向其添加了一些菜单项,然后立即抛出结果。您应该做的是将Window的现有实例作为参数传递给Menubar.Create,如下所示:

        from PySide.QtCore import *
        from PySide.QtGui import *
        # remove the follwing import, which is not needed
        # from ui.window import Window
        
        class MenuBar:
        
            def Create(self, wind):
                # don't create a new instance
                # wind = Window()
                menu = wind.menuBar()
        
                fileMenu = menu.addMenu("File")
                fileMenu.addAction("Exit", exit)
        

        然后在 window.py 中,执行以下操作:

            self.win = QMainWindow()
            ...
            mB = MenuBar()
            mB.Create(self.win)