简体   繁体   中英

How to open a new window with a button click in python?

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_())

I want to open "gui2.ui" when pushButton is clicked.This code is not working .Any help?

You need to convert your Qt designer files to Python files, to do that you can use the command line commands pyuic5 for ui files and pyrcc5 for rc files.

To convert ui files to Python:

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

To convert rc files to Python:

pyrcc5 your_file.rc -o your_file.py

Once you have converted the files, don't modify them directly as they can be regenerated if you make changes to the UI, to use them, inherit from them:

 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM