0

Код из обучалки не работает.

from PyQt5 import QtWidgets
from gui import Ui_MainWindow
import sys
 
 
class mywindow(QtWidgets.QMainWindow):
    def __init__(self):
        super(mywindow, self).__init__()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
 
 
app = QtWidgets.QApplication([])
application = mywindow()
application.show()
 
sys.exit(app.exec())

Выдаёт такую ошибку

Traceback (most recent call last):
File "E:...\SomeName.py", line 3, in
from gui import Ui_MainWindow # импорт нашего сгенерированного файла
ImportError: cannot import name 'Ui_MainWindow' from 'gui' (E:...\gui.py)

gui.py

from PyQt5 import QtCore, QtGui, QtWidgets


class Ui_Dialog(object):
    def setupUi(self, Dialog: object) -> object:
        Dialog.setObjectName("Dialog")
        Dialog.resize(355, 53)
        Dialog.setSizeGripEnabled(True)
        self.FirstR = QtWidgets.QSpinBox(Dialog)
        self.FirstR.setGeometry(QtCore.QRect(0, 30, 71, 21))
        self.FirstR.setObjectName("FirstR")
        self.FinalR = QtWidgets.QSpinBox(Dialog)
        self.FinalR.setGeometry(QtCore.QRect(70, 30, 61, 21))
        self.FinalR.setObjectName("FinalR")
        self.textBrowser = QtWidgets.QTextBrowser(Dialog)
        self.textBrowser.setGeometry(QtCore.QRect(70, 0, 61, 31))
        self.textBrowser.setObjectName("textBrowser")
        self.textBrowser_2 = QtWidgets.QTextBrowser(Dialog)
        self.textBrowser_2.setGeometry(QtCore.QRect(0, 0, 71, 31))
        self.textBrowser_2.setObjectName("textBrowser_2")
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(130, 0, 75, 61))
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(200, 0, 151, 51))
        self.label.setText("")
        self.label.setObjectName("label")

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

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        Dialog.setWhatsThis(_translate("Dialog", "<html><head/><body><p>Calculate XP</p></body></html>"))
        self.textBrowser.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Last round</p></body></html>"))
        self.textBrowser_2.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">First round</p></body></html>"))
        self.pushButton.setText(_translate("Dialog", "Calculate"))


if __name__ == "__main__":
    import sys
    app = QtWidgets.QApplication(sys.argv)
    Dialog = QtWidgets.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())
2
  • 1
    Гриша Хохлова опубликуйте модуль gui,py
    – S. Nick
    7 сен 2022 в 15:24
  • @S.Nick готово! 7 сен 2022 в 17:29

1 ответ 1

0

НИКОГДА НЕ ИЗМЕНЯЙТЕ код, сгенерированный Qt Designer, НИКОГДА.
Создайте другой класс, который наследуется от соответствующего виджета, и используйте созданный класс для его заполнения.

Вы создали форму на основании виджета QDialog, в котором класс называется Ui_Dialog.

Я отметил необходимые изменения, которые вам надо сделать.

import sys
from PyQt5 import QtCore, QtGui, QtWidgets

# --- from gui__ui import Ui_MainWindow
# +++ from gui__ui import Ui_Dialog
# --> vvvvvvvvv <-------> ^^^^^^^^^ <-------------------------------------------
class Ui_Dialog(object):
    def setupUi(self, Dialog: object) -> object:
        Dialog.setObjectName("Dialog")
        Dialog.resize(355, 53)
        Dialog.setSizeGripEnabled(True)
        self.FirstR = QtWidgets.QSpinBox(Dialog)
        self.FirstR.setGeometry(QtCore.QRect(0, 30, 71, 21))
        self.FirstR.setObjectName("FirstR")
        self.FinalR = QtWidgets.QSpinBox(Dialog)
        self.FinalR.setGeometry(QtCore.QRect(70, 30, 61, 21))
        self.FinalR.setObjectName("FinalR")
        self.textBrowser = QtWidgets.QTextBrowser(Dialog)
        self.textBrowser.setGeometry(QtCore.QRect(70, 0, 61, 31))
        self.textBrowser.setObjectName("textBrowser")
        self.textBrowser_2 = QtWidgets.QTextBrowser(Dialog)
        self.textBrowser_2.setGeometry(QtCore.QRect(0, 0, 71, 31))
        self.textBrowser_2.setObjectName("textBrowser_2")
        self.pushButton = QtWidgets.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(130, 0, 75, 61))
        self.pushButton.setObjectName("pushButton")
        self.label = QtWidgets.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(200, 0, 151, 51))
        self.label.setText("")
        self.label.setObjectName("label")

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

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        Dialog.setWhatsThis(_translate("Dialog", "<html><head/><body><p>Calculate XP</p></body></html>"))
        self.textBrowser.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">Last round</p></body></html>"))
        self.textBrowser_2.setHtml(_translate("Dialog", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n"
"<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
"p, li { white-space: pre-wrap; }\n"
"</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n"
"<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">First round</p></body></html>"))
        self.pushButton.setText(_translate("Dialog", "Calculate"))

 
# class mywindow(QtWidgets.QMainWindow):
class MyWindow(QtWidgets.QDialog):
# ---------------------> ^^^^^^^ <-------------------------------------------

    def __init__(self):
        super(MyWindow, self).__init__()
#        self.ui = Ui_MainWindow()
        self.ui = Ui_Dialog()                                        # !!! +++
        
        self.ui.setupUi(self)
        
        # тут ваша логика
 

if __name__ == "__main__": 
    app = QtWidgets.QApplication(sys.argv)
    application = MyWindow()
    application.show()
    sys.exit(app.exec())

введите сюда описание изображения


Update

  1. Зайдите в Qt Designer. Во всплывающем окне 'Новая форма' выберите Main Window и нажмите 'Создать'. Далее вы создаете нужную вам форму и сохраняете ее в файл gui.ui.

введите сюда описание изображения

  1. Выполните: python -m PyQt5.uic.pyuic -x gui.ui -o gui.py

  2. Запускаете ваш SomeName.py

    import sys
    from PyQt5 import QtWidgets
    from gui import Ui_MainWindow
    
    
    class MyWindow(QtWidgets.QMainWindow):
        def __init__(self):
            super(MyWindow, self).__init__()
    
            self.ui = Ui_MainWindow()
            self.ui.setupUi(self)
    
    
    if __name__ == '__main__': 
        app = QtWidgets.QApplication([])
        application = MyWindow()
        application.show()
    
        sys.exit(app.exec())
    
9
  • я правильно поняла, что код писать прям в файле gui.py? 7 сен 2022 в 18:51
  • Просто у меня примерно та же ошибка Traceback (most recent call last): File "E:\...\SomeName.py", line 3, in <module> from gui import Ui_MainWindow # импорт нашего сгенерированного файла ImportError: cannot import name 'Ui_MainWindow' from 'gui' (E:\...\gui.py) 7 сен 2022 в 18:57
  • @ГришаХохлова я же вам все отметил и написал. В модуле gui.py НЕТ класса Ui_MainWindow(). Замените from gui__ui import Ui_MainWindow на from gui__ui import Ui_Dialog или зайдите в Qt Designer и создайте новую форму наследуясь от класса QMainWindow и сконвертируйте новый gui.py, тогда в вашем main.py ничего менять не надо.
    – S. Nick
    7 сен 2022 в 19:18
  • Я поменяла имя на MainWindow и вот ошибка Traceback (most recent call last): File "E:\...\SomeName.py", line 15, in <module> application = mywindow() File "E:\Калькулятор экспы\Front end.py", line 11, in init self.ui.setupUi(self) File "E:\...\gui.py", line 19, in setupUi MainWindow.setSizeGripEnabled(True) AttributeError: 'mywindow' object has no attribute 'setSizeGripEnabled' 8 сен 2022 в 8:03
  • @ГришаХохлова Я добавил обновление в свой ответ. Выполните все по шагам как я описал для вас. Если мой ответ помог вам, то не забудьте пометить как правильный, если вы не знаете, как это сделать, проверьте ru.stackoverflow.com/tour
    – S. Nick
    8 сен 2022 в 13:12

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.