[英]failed to open a new window after push button pyqt5
我學習pyqt5並嘗試通過單擊另一個窗口中的按鈕來打開新窗口。 如果沒有input()函數,它將立即關閉打開的窗口,所以我放了input()來保持窗口打開。 該窗口將打開很長時間,但隨后已停止工作。 有人能幫我嗎 ? 謝謝
import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App1(QWidget):
def __init__(self):
super().__init__()
self.title = 'open window'
self.left = 60
self.top = 60
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
m.getch()
input() '''here is the problem'''
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 200
self.top = 200
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100, 70)
button.clicked.connect(self.on_click)
self.show()
@pyqtSlot()
def on_click(self):
app1 = QApplication(sys.argv)
ex1 = App1()
sys.exit(app1.exec_())
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
您需要保存對窗口的引用,否則在on_click()
完成執行時將被垃圾回收。 最簡單的方法是通過使用self
將其存儲在App
中
@pyqtSlot()
def on_click(self):
self.ex1 = App1()
import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App1(QWidget):
def __init__(self):
super().__init__()
self.title = 'open window'
self.left = 60
self.top = 60
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.show()
input()
class App(QMainWindow):
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 200
self.top = 200
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100, 70)
button.clicked.connect(self.on_click)
self.show()
@pyqtSlot()
def on_click(self):
self.ex1 = App1()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.