简体   繁体   中英

PyQt5 GUI can't be close from Spyder

I am trying to create a simple GUI using PyQt5. I am running my code in windows 10 from Spyder(Anaconda latest version, python 3.7). Here is my code:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button test'
        self.left = 50
        self.top = 50
        self.width = 720
        self.height = 800
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100,70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):
        print('PyQt5 button click')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    app.exec_()

A window pop up. Now if I close the GUI by clicking on closing button(top right corner of the GUI),Spyder IP console does not return to normal condition. It freezes. What should I use in code to solve the issue?

Thanks, Moni

Closing the window doesn't appear to close the QApplication object. To do this, override the closeEvent function of the main window by adding these two lines after the on_Click definition

  def closeEvent(self,event):
     QApplication.quit()

This will close the window and the QApplication object as well and control should return to the console

You can try and look at the answer in the following thread: Can't Kill PyQT Window after closing it. Which requires me to restart the kernal

Seems to have resemblance to your problem and a solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM