Pyqt5 名称错误

问题描述 投票:0回答:1

我试图找出为什么这会给我一个名称错误。类名

App(QDialog):
是有错误的类名。我完全按照 YouTube 视频进行操作,虽然他的代码可以工作,但我的代码却不能。

接下来我可以尝试什么?

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QMessageBox, QBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QTableWidget, QTableWidgetItem
from PyQt5.QtWidgets import QInputDialog, QLineEdit


class App(QDialog):

    def __init__(self):
        super().__init__()
        self.title = "PyQt5 example - pythonspot.com"
        self.left = 10
        self.right = 10
        self.width = 640
        self.height = 400
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        age = self.getAge()
        print(age)

        self.show()

    def getAge(self):
        age, okPressed = QInputDialog.getInt(self, "Get Integer", "Age:", 18, 16, 130, 1)
        if okPressed:
            return age


if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
python-3.x pyqt pyqt5
1个回答
4
投票
NameError: name 'QDialog' is not defined

您收到此错误是因为您忘记导入 QDialog。只需将其添加到 QWidgets 导入之一的末尾,例如:

from PyQt5.QtWidgets import QInputDialog, QLineEdit, QDialog

此外,您将收到属性错误,因为 self.top 被调用,但从未定义。在init函数中添加:

def __init__(self):
    super().__init__()
    self.title = "PyQt5 example - pythonspot.com"
    self.left = 10
    self.right = 10
    self.width = 640
    self.height = 400
    self.top = 10
    self.initUI()
© www.soinside.com 2019 - 2024. All rights reserved.