所以我最近开始学习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)
答案 0 :(得分:0)
如果仔细查看追溯,您会看到:
ui.window
然后:
ui.menubar
然后:
ui.window
现在我们进入无限循环的导入,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)