【PyQt】点击一个窗口的按钮来打开另一个窗口

先在qt designer 中设计好两个窗口(main和second)如图【PyQt】点击一个窗口的按钮来打开另一个窗口_第1张图片【PyQt】点击一个窗口的按钮来打开另一个窗口_第2张图片

在vscode 中将 相应的ui 文件 编译成python文件

【PyQt】点击一个窗口的按钮来打开另一个窗口_第3张图片

修改 UI_main.py 为main窗口中的按钮添加点击事件

UI_main.py
from PyQt5 import QtCore, QtGui, QtWidgets
from Ui_second import Ui_Form


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(308, 312)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.pushButton = QtWidgets.QPushButton(self.centralwidget)
        self.pushButton.setObjectName("pushButton")

        self.pushButton.clicked.connect(self.popWindow) #为按钮添加点击事件

        self.gridLayout.addWidget(self.pushButton, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.pushButton.setText(_translate("MainWindow", "弹窗"))

    #显示第二窗口的函数(与 UI_second.py 中自动生成的相应的main 函数中的内容一致)
    def popWindow(self):
        self.form2 = QtWidgets.QWidget() 
        self.ui2 = Ui_Form()
        self.ui2.setupUi(self.form2)
        self.form2.show() 
        

if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

UI_second.py
from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Form(object):
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(400, 300)
        self.label = QtWidgets.QLabel(Form)
        self.label.setGeometry(QtCore.QRect(140, 130, 81, 18))
        self.label.setObjectName("label")

        self.retranslateUi(Form)
        QtCore.QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Form"))
        self.label.setText(_translate("Form", "第二界面"))


""" if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Form = QtWidgets.QWidget()
    ui = Ui_Form()
    ui.setupUi(Form)
    Form.show()
    sys.exit(app.exec_()) """

效果

【PyQt】点击一个窗口的按钮来打开另一个窗口_第4张图片

你可能感兴趣的:(【PyQt】点击一个窗口的按钮来打开另一个窗口)