我想在spyder环境中用PyQt5创建一个QMainWindow。为此,我编写了以下脚本:
try:
from PyQt4.QtCore import QEventLoop
except:
try:
from PyQt5.QtCore import QEventLoop
except:
pass
def launchGUI(windowTitle="Title"):
# Import the recquired PyQt packages
try:
from PyQt4.QtGui import (
QPushButton, QMainWindow, QVBoxLayout, QWidget)
except:
try:
from PyQt5.QtWidgets import (
QPushButton, QMainWindow, QVBoxLayout, QWidget)
except:
print("you need PyQt4 or PyQt5 to display images")
return
# ---- Main window class
class MainWnd(QMainWindow):
def __init__(self, title, parent=None):
super(MainWnd, self).__init__(parent)
self.eventLoop = QEventLoop()
# Main widget, containing the entire window
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
mainLayout = QVBoxLayout()
centralWidget.setLayout(mainLayout)
# Validation button
self.buttonOK = QPushButton("Ok")
self.buttonOK.clicked.connect(self.buttonOKClicked)
mainLayout.addWidget(self.buttonOK)
# Display the window
self.setWindowTitle(title)
self.show()
def buttonOKClicked(self):
# Mark the threshold as validated and close the window
self.bValidated = True
self.close()
def closeEvent(self, *args, **kwargs):
# Stop the event loop
self.eventLoop.exit()
def exec(self):
# Loop to wait the window closure
self.eventLoop.exec()
# Create and display the Qt window and wait for its closure
w = MainWnd(windowTitle)
w.exec()
def main():
app = QtCore.QCoreApplication.instance()
if app is None:
app = QApplication([])
launchGUI()
# app.exec_()
if __name__ == "__main__":
# import necessary Qt modules
# display an error message and abort if importation fails
bPyQtLoadSuccessful = True
try:
from PyQt4 import QtCore
from PyQt4.QtGui import QApplication
except:
try:
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication
except:
print("you need PyQt4 or PyQt5 to display images")
bPyQtLoadSuccessful = False
if bPyQtLoadSuccessful:
main()
我在诸如here和here这样的多个来源中看到,由于spyder创建了QApplication的实例,因此我需要测试该实例是否存在。但是,当我在两台不同的计算机上启动此脚本时,会得到两种不同的行为。在第一个窗口中(Windows 10),当我注释第74至76行(如果尚未创建QApplication实例,则对其进行注释)和第86至95行(以导入QApplication实例)时,将按预期方式发生错误"kernel died, restarting"
所需的软件包)。在第二个窗口(Windows 7)中,我没有收到此错误,并且出现了窗口,我可以使用它。
当我在控制台中以建议的here使用.\spyder.exe --show-console
启动spyder时,没有显示日志错误。
我检查了spyder,python和Qt的版本,它们都匹配:spyder 3.2.4,Python 3.6.3,Qt 5.6.2。 A还检查了模块,唯一的区别是openCV仅安装在Windows 7计算机中,而不安装在Windows 10中,但我不使用它。
这种差异是由操作系统引起的还是在某种情况下使脚本可以工作?