我想在按下按钮时打开第二个窗口。窗口打开并立即关闭。有人知道我在做什么吗?
这是我的代码:
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_())
只需将您的open_second_screen
更改为:
def open_second_screen(self):
self.second_window = SecondWindow()
self.second_window.show()
(当然,从其他类中删除self.show(((
这是PYQT的可再生问题。如果不存储在变量中,则收集新窗口,并且当功能结束时删除second_window
变量,除非您将其存储为窗口实例的参数。