PyQt4 AttributeError:' Ui_MainWindow'对象没有属性'文件名'

时间:2015-06-03 09:04:43

标签: python pyqt4

我正在为文本编辑器编写一些GUI,然后我想添加消息框以确认是否保存更改。 这是我的示例代码

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
    return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(616, 554)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.open_btn = QtGui.QPushButton(self.centralwidget)
        self.open_btn.setGeometry(QtCore.QRect(110, 300, 97, 31))
        self.open_btn.setObjectName(_fromUtf8("open_btn"))
        self.close_btn = QtGui.QPushButton(self.centralwidget)
        self.close_btn.setGeometry(QtCore.QRect(330, 300, 97, 31))
        self.close_btn.setObjectName(_fromUtf8("close_btn"))
        self.textEdit = QtGui.QTextEdit(self.centralwidget)
        self.textEdit.setGeometry(QtCore.QRect(110, 60, 311, 201))
        self.textEdit.setObjectName(_fromUtf8("textEdit"))
        self.save_btn = QtGui.QPushButton(self.centralwidget)
        self.save_btn.setGeometry(QtCore.QRect(220, 300, 97, 31))
        self.save_btn.setObjectName(_fromUtf8("save_btn"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 616, 27))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QObject.connect(self.close_btn,     QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.close)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
     # text editor open slot added
    QtCore.QObject.connect(self.open_btn,QtCore.SIGNAL("clicked()"), self.file_dialog)
    QtCore.QObject.connect(self.save_btn,QtCore.SIGNAL("clicked()"), self.file_save)
    QtCore.QObject.connect(self.textEdit,QtCore.SIGNAL("textChanged()"), self.enable_save)
    QtCore.QMetaObject.connectSlotsByName(MainWindow)
# improved code to open and cancle button    
    def file_dialog(self):
    response = False
    # buttons texts
    SAVE = 'Save'
    DISCARD = 'Discard'
    CANCEL = 'Cancel'
    # if we have changes then ask about them
    if self.save_btn.isEnabled() and self.filename:
        message = QtGui.QMessageBox(self)
        message.setText('What to do about unsaved changes ?')
        message.setWindowTitle('Notepad')
        message.setIcon(QtGui.QMessageBox.Question)
        message.addButton(SAVE, QtGui.QMessageBox.AcceptRole)
        message.addButton(DISCARD, QtGui.QMessageBox.DestructiveRole)
        message.addButton(CANCEL, QtGui.QMessageBox.RejectRole)
        message.setDetailedText('Unsaved changes in file: ' + str(self.filename))
         message.exec_()
        response = message.clickedButton().text()
        # save  file
        if response == SAVE:
            self.file_save()
            self.save_btn.setEnabled(False)
        # discard changes
        elif response == DISCARD:
            self.save_btn.setEnabled(False)
    # if we didn't cancelled show the file dialogue
    if response != CANCEL:
        fd=QtGui.QFileDialog(None)
        self.filename = fd.getOpenFileName()
        from os.path import isfile
        if isfile(self.filename):
            import codecs
            text = codecs.open(self.filename,'r','utf-8').read()
            self.textEdit.setPlainText(text)
            self.save_btn.setEnabled(False)


    def enable_save(self):
        self.save_btn.setEnabled(True)
#save btn
    def file_save(self):
        from os.path import isfile
        if isfile(self.filename):
            import codecs
            s = codecs.open(self.filename,'w','utf-8')
            s.write(unicode(self.textEdit.toPlainText()))
            s.close()

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.open_btn.setText(_translate("MainWindow", "Open", None))
        self.close_btn.setText(_translate("MainWindow", "Close", None))
        self.save_btn.setText(_translate("MainWindow", "Save", None))


if __name__ == "__main__":
    import sys
    app = QtGui.QApplication(sys.argv)
    MainWindow = QtGui.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

尝试运行时,我得到了

Traceback (most recent call last):
  File "texteditor.py", line 69, in file_dialog
    if self.save_btn.isEnabled() and self.filename:
AttributeError: 'Ui_MainWindow' object has no attribute 'filename'

第69行我

if self.save_btn.isEnabled() and self.filename:
            message = QtGui.QMessageBox(self)

任何解决方案? 谢谢

1 个答案:

答案 0 :(得分:0)

在第69行调用self.filename时,尚未设置该属性。

如果添加以下行:

self.filename = ''

...在setupUi函数中的某个地方,这应解决问题。