我从另一个窗口打开的新 python gui 窗口一打开就退出.我该如何解决这个问题 [英] My new python gui window opened from another window exits as soon as it opens.How do I fix this
本文介绍了我从另一个窗口打开的新 python gui 窗口一打开就退出.我该如何解决这个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了 python pyqt 代码,用于在单击按钮时打开一个带有来自另一个窗口的标签的新窗口.问题是,新窗口一打开就退出.我该如何解决这个问题.
I have written python pyqt code to open a new window with a label from another window on a button click. The issue is ,new window exits as soon as it opens.How do i fix this.
我写的代码是
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(display)
self.show()
class display(QtGui.QWidget):
def __init__(self):
super(display,self).__init__()
self.lab=QtGui.QLabel()
self.lab.setText("hi")
self.show()
def main():
App=QtGui.QApplication(sys.argv)
Gui=Window()
sys.exit(App.exec_())
main()
推荐答案
您需要保留对第二个窗口的 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()
这篇关于我从另一个窗口打开的新 python gui 窗口一打开就退出.我该如何解决这个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文