How to reopen window

2019-03-03 12:52发布

问题:

The following code should close the current file and open it again. Instead, it keeps opening only new windows.

Does anybody have a hint for keeping the old window closed?

import sys
from PyQt4 import QtGui, QtCore
import subprocess 

class Example(QtGui.QWidget):
    def __init__(self):
        super(Example, self).__init__()
        self.initUI()

    def run(self, path):
        subprocess.call(['python',path])

    def initUI(self):
        self.close()
        self.btn_newSearch = QtGui.QPushButton('Start', self)
        self.btn_newSearch.clicked.connect(lambda:self.run('tests.py'))

        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Python Script')
        self.show()

def main():
    app = QtGui.QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

回答1:

You seem to have put self.close() in the wrong place. Also, you should not use subprocess.call, as it will block until the command completes. It's better to use QProcess instead:

    def run(self, path):
        QtCore.QProcess.startDetached('python', [path])
        self.close()

    def initUI(self):
        self.btn_newSearch = QtGui.QPushButton('Start', self)
        ...