我尝试使用 PyQt5 和以下代码关闭和打开窗口:
import PyQt5.QtWidgets as qtw
from PyQt5 import uic
import sys
import os
class Window2(qtw.QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi("window2.ui",self)
class MainWindow(qtw.QMainWindow):
def __init__(self):
super().__init__()
uic.loadUi("selectWindow.ui",self)
self.path = os.path.abspath(os.path.dirname(sys.argv[0]))
self.pbStart.clicked.connect(self.showData)
def showData(self):
print(self.leInput.text())
self.w = Window2()
self.w.show()
self.hide()
if __name__ == '__main__':
app = qtw.QApplication(sys.argv)
win = MainWindow()
win.show()
sys.exit(app.exec_())
出现第一个窗口,我可以输入一些值并按下按钮,但随后出现以下错误:
$ python selectWindow.py
3
Traceback (most recent call last):
File "D:\DEV\Fiverr2024\TRY\artfulrooms\selectWindow.py", line 20, in showData
self.w = Window2()
^^^^^^^^^
File "D:\DEV\Fiverr2024\TRY\artfulrooms\selectWindow.py", line 9, in __init__
uic.loadUi("window2.ui",self)
File "D:\DEV\.venv\pyqt\Lib\site-packages\PyQt5\uic\__init__.py", line 241, in loadUi
return DynamicUILoader(package).loadUi(uifile, baseinstance, resource_suffix)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\DEV\.venv\pyqt\Lib\site-packages\PyQt5\uic\Loader\loader.py", line 66, in loadUi
return self.parse(filename, resource_suffix)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\DEV\.venv\pyqt\Lib\site-packages\PyQt5\uic\uiparser.py", line 1037, in parse
actor(elem)
File "D:\DEV\.venv\pyqt\Lib\site-packages\PyQt5\uic\uiparser.py", line 822, in createUserInterface
self.toplevelWidget = self.createToplevelWidget(cname, wname)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\DEV\.venv\pyqt\Lib\site-packages\PyQt5\uic\Loader\loader.py", line 57, in createToplevelWidget
raise TypeError(
TypeError: ('Wrong base class of toplevel widget', (<class '__main__.Window2'>, 'QDialog'))
如何关闭实际窗口并打开新窗口2?
我为你制作了虚拟项目,看看它是如何工作的
from PyQt6 import QtGui, QtCore , QtWidgets
import sys
class Window2(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Window2, self).__init__(parent)
class Window1(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super(Window1, self).__init__(parent)
self.pushButton = QtWidgets.QPushButton("click me")
self.setCentralWidget(self.pushButton)
self.pushButton.clicked.connect(self.on_pushButton_clicked)
def on_pushButton_clicked(self):
dialog = Window2(self)
dialog.closeEvent = lambda event:self.show()
dialog.show()
self.hide()
def main():
app = QtWidgets.QApplication(sys.argv)
main = Window1()
main.show()
sys.exit(app.exec())
if __name__ == '__main__':
main()
所以你可以根据需要更改它
dialog.closeEvent = lambda event:self.show()
它用于在 window1
关闭时打开 window2
,因此如果您需要在 window2
关闭后执行更多操作(例如在数据库中保存一些数据),只需更改它即可
dialog.closeEvent = self.yourfunc
并将 def yourfunc(self,event)
添加到您的代码中,如下所示
def showWindow1(self,event):
self.show()
def on_pushButton_clicked(self):
dialog = Window2(self)
dialog.closeEvent = self.showWindow1
dialog.show()
self.hide()