我想在按下按钮时打开第二个窗口。窗口打开并立即关闭。有人知道我在做什么错吗?
这是我的代码:
import sys
from PyQt5 import QtGui
from PyQt5.QtWidgets import QMainWindow, QPushButton, QLabel, QApplication
class FirstWindow(QMainWindow):
def __init__(self):
super(FirstWindow, self).__init__()
self.setGeometry(50, 50, 500, 300)
self.setWindowTitle('It\'s working!')
self.initUI()
def initUI(self):
second_screen_btn = QPushButton('Open second screen', self)
second_screen_btn.setGeometry(250, 100, 100, 100)
second_screen_btn.clicked.connect(self.open_second_screen)
self.show()
def open_second_screen(self):
second_window = SecondWindow()
class SecondWindow(QMainWindow):
def __init__(self):
super(SecondWindow, self).__init__()
self.setGeometry(100, 100, 500, 300)
self.setWindowTitle('This is a second window')
self.initUI()
def initUI(self):
self.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
gui = FirstWindow()
sys.exit(app.exec_())
答案 0 :(得分:2)
只需将您的open_second_screen
更改为此:
def open_second_screen(self):
self.second_window = SecondWindow()
self.second_window.show()
(当然,还要从另一个类中删除self.show())
这是PyQt的一个经常出现的问题。如果新窗口未存储在变量中,则将对其进行垃圾回收;除非函数将second_window
存储为窗口实例的参数,否则它将{{1}}删除。