【问题标题】:Pyqt5 NameErrorPyqt5 名称错误
【发布时间】:2017-02-10 03:17:12
【问题描述】:

我试图找出为什么这会给我一个 NameError.... 类名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】:
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()

【讨论】:

  • 可能self.right应该替换为self.top
猜你喜欢
  • 2019-01-12
  • 2019-11-05
  • 2017-06-30
  • 2021-01-23
  • 2015-05-29
  • 1970-01-01
相关资源
最近更新 更多