1

我在尝试做一个非常简单的用户界面时遇到了问题。我用 Qt Designer 制作了我的 UI,然后用 pyuic4 我得到了我的 python 代码。然后我编写了我需要的函数,并用 Eclipse IDE 编译。

我从 pyuic4 得到的代码是:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'Dni.ui'
#
# Created: Sat Apr 14 02:44:34 2012
#      by: PyQt4 UI code generator 4.9.1
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    _fromUtf8 = lambda s: s

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(371, 217)
        Dialog.setMinimumSize(QtCore.QSize(371, 217))
        self.layoutWidget = QtGui.QWidget(Dialog)
        self.layoutWidget.setGeometry(QtCore.QRect(30, 30, 311, 151))
        self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
        self.gridLayout = QtGui.QGridLayout(self.layoutWidget)
        self.gridLayout.setMargin(0)
        self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
        self.label = QtGui.QLabel(self.layoutWidget)
        self.label.setObjectName(_fromUtf8("label"))
        self.horizontalLayout.addWidget(self.label)
        self.entrada = QtGui.QLineEdit(self.layoutWidget)
        self.entrada.setObjectName(_fromUtf8("entrada"))
        self.horizontalLayout.addWidget(self.entrada)
        self.gridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.boton = QtGui.QPushButton(self.layoutWidget)
        self.boton.setObjectName(_fromUtf8("boton"))
        self.gridLayout.addWidget(self.boton, 1, 0, 1, 1)
        self.horizontalLayout_2 = QtGui.QHBoxLayout()
        self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
        self.label_3 = QtGui.QLabel(self.layoutWidget)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.horizontalLayout_2.addWidget(self.label_3)
        self.salida = QtGui.QLineEdit(self.layoutWidget)
        self.salida.setObjectName(_fromUtf8("salida"))
        self.horizontalLayout_2.addWidget(self.salida)
        self.gridLayout.addLayout(self.horizontalLayout_2, 2, 0, 1, 1)
        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
        self.label.setText(QtGui.QApplication.translate("Dialog", "Introduzca su DNI", None, QtGui.QApplication.UnicodeUTF8))
        self.boton.setText(QtGui.QApplication.translate("Dialog", "Hallar NIF", None, QtGui.QApplication.UnicodeUTF8))
        self.label_3.setText(QtGui.QApplication.translate("Dialog", "NIF:", None, QtGui.QApplication.UnicodeUTF8))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    Dialog = QtGui.QDialog()
    ui = Ui_Dialog()
    ui.setupUi(Dialog)
    Dialog.show()
    sys.exit(app.exec_())

我用我需要的功能制作的代码:

from Dni import Ui_Dialog
from PyQt4 import QtCore, QtGui

LETRADNI = {0:'T', 1:'R', 2:'W', 3:'A', 4:'G', 5:'M', 6:'Y', 7:'F', 8:'P', 9:'D', 10:'X', 11:'B', 12:'N',
            13: 'J', 14:'Z', 15:'S', 16:'Q', 17:'V', 18:'H', 19:'L', 20:'C', 21:'K', 22:'E'}


# Se hereda de la clase QtGui.QMainWindow
class Principal(QtGui.QMainWindow):
    # Se define el constructor de la clase __init__
    def __init__(self):
        # Se llama al constructor de la clase padre
        QtGui.QMainWindow.__init__(self)

        # Se crea la instancia de Ui_Dialog
        self.ventana = Ui_Dialog()
        self.ventana.setupUi(self)

        # Se conectan las señales con los slots
        self.connect(self.ventana.boton,QtCore.SIGNAL('clicked()'), self.letradni)


def Calcula_letra_dni(dni):
    '''Función Calcula_letra_dni:

        Funcionamiento:

            La función recibe el valor entero dni. Posteriormente calculará el resto de la división
            por 23. Éste número se buscará en el diccionario 'LETRADNI' para obtener la letra correspondiente
            a ese DNI.

        Argumentos

            dni -- número del documento nacional de identidad (int)

        Devuelve:

            Una cadena (string) -- DNI + letra preparado para salida por pantalla
    '''
    #if len(str(dni))>8 & len(str(dni))<7:
    #    raise ValueError('El dni debe tener entre 7 y 8 cifras')

    num_letra = dni % 23.0

    letra = LETRADNI[num_letra]

    return '{0}-{1}'.format(dni,letra)


def letradni(self):
    self.ventana.salida.setText(Calcula_letra_dni(self.ventana.entrada.text()))

第一个编译并运行,它完美地显示了我的用户界面。

编译第二个我得到一个错误,上面写着:

Description                                 Resource  Path  Location   Type
Undefined variable from import: QString Dni.py    /Dni  line 18    PyDev Problem

谁能帮我?

提前致谢。

4

1 回答 1

3

首先,我认为您列出的实际问题与 Eclipse、pydev 和您的项目 PYTHONPATH 有关。查看此内容以确保您已正确设置所有内容并将 PyQt4 包含在您的 pythonpath 中:http:
//popdevelop.com/2010/04/setting-up-ide-and-creating-a-cross-platform-qt-python- gui-应用程序/

在那之后,除了你提到的之外,你的代码似乎还有一些问题......

首先定义Principal类,然后定义Calcula_letra_dni函数,然后定义看起来像类实例方法的东西letradni,它应该是Principal

class Principal(QtGui.QMainWindow):
    # Se define el constructor de la clase __init__
    def __init__(self):
        ...

    def letradni(self):
        ...


def Calcula_letra_dni(dni):
    ...

然后,当您尝试对字符串进行数学运算(感谢@Avaris)并浮动时,看起来您会引发异常:
num_letra = dni % 23.0

您可能应该先将该字符串转换为浮点数: num_letra = float(dni) % 23.0

最后,我认为您也忘记main为您的应用程序定义一个。您有一个在您的 中自动生成的Dni.py,但您没有为您的实际入口点脚本编写一个:

if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    form = Principal()
    form.show()
    sys.exit(app.exec_())
于 2012-04-14T02:53:37.670 回答