且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我从另一个窗口打开的新 python gui 窗口一打开就退出.我该如何解决这个问题

更新时间:2023-09-14 10:50:34

您需要保留对第二个窗口的 QWidget 对象的引用.当前,当您单击按钮时,会触发 clicked 信号并调用 disp1.这会创建小部件,但它会立即被垃圾收集.

You need to keep a reference to the QWidget object for your second window. Currently when you click the button, the clicked signal is fired and it calls disp1. That creates the widget, but then it is immediately garbage collected.

改为这样做以保留参考:

Instead do this to keep a reference:

import sys
from PyQt4 import QtGui,QtCore

class Window(QtGui.QWidget):
    def __init__(self):
        super(Window,self).__init__()
        self.btn=QtGui.QPushButton('button',self)

        self.btn.clicked.connect(self.open_new_window)
        self.show()

    def open_new_window(self):
        # creates the window and saves a reference to it in self.second_window
        self.second_window = disp1()

class displ(QtGui.QWidget):
    def __init__(self):
        super(displ,self).__init__()
        self.lab=QtGui.QLabel()
        self.lab.setText("hello")
        self.show()

def main():
    App=QtGui.QApplication(sys.argv)
    Gui=Window()
    sys.exit(App.exec_())

main()