Pyqt5 NameError

别来无恙 提交于 2020-08-20 08:04:04

问题


I am trying to find why this gives me a NameError.... Class name App(QDialog): is the one that has the error. I was following exactly as youtube video, while his code works, mine doesn't. Please help me on this. Thanks :)

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

回答1:


NameError: name 'QDialog' is not defined

You are getting this error because you forgot to import QDialog. Just add it to the end of one of your QWidgets imports such as:

from PyQt5.QtWidgets import QInputDialog, QLineEdit, QDialog

Also, you are going to get an attribute error because self.top is called, but never defined. Add it in the init function:

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


来源:https://stackoverflow.com/questions/42150905/pyqt5-nameerror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!