如何在python中单击按钮打开新窗口?

时间:2018-07-25 07:24:44

标签: python pyqt5

import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.uic import *
class new1(QDialog):
    def __init__(self):
        super(new1, self).__init__()
        loadUi('gui.ui',self)
        self.setWindowTitle("New Window")
        self.pushButton.clicked.connect(self.clicked1)
    def clicked1(self):
        loadUi('gui2.ui',self)


app=QApplication(sys.argv)
widget=new1()
widget.show()

sys.exit(app.exec_())

单击按钮时我想打开“ gui2.ui”。此代码不起作用。有帮助吗?

1 个答案:

答案 0 :(得分:0)

您需要将Qt设计器文件转换为Python文件,为此,您可以将命令行命令pyuic5用于ui文件,将pyrcc5用于rc文件。

要将ui文件转换为Python:

pyuic5 --import-from=widgets -x your_file.ui -o your_file.py

要将rc文件转换为Python:

pyrcc5 your_file.rc -o your_file.py

一旦您转换了文件,请勿直接修改它们,因为如果您对UI进行更改,可以重新生成它们,以使用它们并从它们继承:

 class Gui2Dialog(Ui_Gui2, QDialog):
    def __init__(self):
        Ui_Gui2.__init__(self)
        QDialog.__init__(self)

        self.setupUi(self)

        self.setWindowTitle("Gui 2")

class GuiDialog(Ui_Gui, QDialog):
    def __init__(self):
        Ui_Gui.__init__(self)
        QDialog.__init__(self)

        self.setupUi(self)

        self.setWindowTitle("New Window")
        self.pushButton.clicked.connect(self.clicked1)

    def clicked1(self):
        gui2_dialog = Gui2Dialog()
        gui2_dialog.exec_()
        gui2_dialog.show()