16
  • Using Spyder in Python 3.5.2 |Anaconda 4.2.0 (64-bit) Windows package. qt: 5.6.0
  • For first run, GUI window opens as expected
  • For 2nd run, nothing opens, and receiving Kernel died, restarting log message.

gui1.py:

import sys from PyQt5.QtWidgets import QApplication, QWidget

app = QApplication(sys.argv)

w = QWidget()

w.resize(250,150) w.show()

#sys.exit(app.exec_()) 
app.exec_()

IPhython log:

runfile('F:/work/ws_python/TestProj1/gui1/gui1.py', wdir='F:/work/ws_python/TestProj1/gui1')

runfile('F:/work/ws_python/TestProj1/gui1/gui1.py', wdir='F:/work/ws_python/TestProj1/gui1')

Kernel died, restarting

Kernel died, restarting

Kernel died, restarting

Why kernel dies for 2nd run and how to solve it?

(Doing the same even using #sys.exit(app.exec_()) as last line.)

Thomas K
  • 39,200
  • 7
  • 84
  • 86
Daniel Hári
  • 7,254
  • 5
  • 39
  • 54
  • Qt may not like you creating more than one `QApplication` object in the same process. You can use `QtCore.QCoreApplication.instance()` to get the application instance if one was already created. [Code example](https://github.com/ipython/ipython/blob/master/examples/IPython%20Kernel/gui/gui-qt.py). – Thomas K Oct 18 '16 at 09:19
  • Could you provide an example for my case? It does not work for me. – Daniel Hári Oct 18 '16 at 20:17
  • 4
    I think the important bit is to get the existing instance of the application if it exists: `app = QtCore.QCoreApplication.instance()`. Then, if it doesn't exist, create a new application: `if app is None: app = QtGui.QApplication()`. – Thomas K Oct 19 '16 at 10:49

3 Answers3

20

This code fixed the problem, thanks for the hint.

app = QtCore.QCoreApplication.instance()
if app is None:
    app = QtWidgets.QApplication(sys.argv)
Corky Benson
  • 201
  • 2
  • 5
4

This works better for the kernel died, restarting error.

from PyQt5.QtWidgets import QApplication, QDialog
from PyQt5.QtCore import QCoreApplication

#app = QApplication(sys.argv)
app = QCoreApplication.instance()
if app is None:
    app = QApplication(sys.argv)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
badsaah6
  • 41
  • 1
0

For me the above solution worked but only as long as the window-close button (from the Window decoration) was used to close the main window. But the problem still was present when the program was terminated from a GUI signal handler, reacting e.g. to a button being clicked. After much fiddling, I learned that a safe enough way for terminating in this situation is as follows:

def safeExit(self):
    """exit the application gently so Spyder IDE will not hang"""
    self.ui.deleteLater()
    self.ui.close()
    self.ui.destroy()


... self.ui.Button2.clicked.connect(self.safeExit) ...
T.E.
  • 1
  • 1