pyqt5 关于主窗口闪退

窗口闪退

from PyQt5.QtWidgets import *
import sys


class Main(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("主窗口")
        button = QPushButton("弹出子窗口", self)
        button.clicked.connect(self.show_child)  # 关联子窗口调用函数

    def show_child(self):
        child_window = Child()
        child_window.show()

class Child(QDialog):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("子窗口")

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = Main()
    window.show()
    sys.exit(app.exec_())

程序中调用QDialog的show()方法,运行后点击按钮,子窗口会一闪而过,它的实例为父窗口show_child()方法中的局部变量,当窗口显示后,父窗口的show_child()方法继续执行,当方法运行完后,python的回收机制就把局部变量销毁了,相当于子窗口实例被销毁,故子窗口一闪而过。

将child_window改为类属性就不会有这种问题

def show_child(self):
        self.child_window = Child()
        self.child_window.show()
原文地址:https://www.cnblogs.com/gexbooks/p/13140018.html