python和pyqt5编写的软件为何闪退

本人解释,这个标题纯属噱头,为了赚一点点击率,其实应该叫,《用python的catch捕获无关紧要的异常》。
废话不多说,上实际情况。

    def open(self):
        strFilter="document file(*.docx);;text file(*.txt)"
        fileName,_=QFileDialog.getOpenFileName(self,'选择要打开的文件','c:\\',strFilter,"document file(*.docx)")
        if(fileName.endswith("txt"))
                file=QFile()
                file.setFileName(fileName)
                strText=str()
                if(file.open(QFile.ReadOnly|QFile.Text)):
                    input=QTextStream(file)
                    strText=input.readAll()
                print(strText)
                self.textEdit.setText(strText)
        else:
                strText=""
                document = Document(fileName)
                for paragraph in document.paragraphs:
                    strText+=paragraph.text
                print(strText)
                self.textEdit.setText(strText)

这段代码大意是通过python自带的open和python读取word的document模块来达到选择电脑上的word或者txt文件打开并读写到textEdit控件的目的。事实证明它运行的很好。
在这里插入图片描述
但是有个问题,如果我不选择文件并关闭对话框,我的代码中因为缺少处理打开文件内容为空的部分,这时候就会报错闪退,虽然它明明对我的程序没什么影响。这时有两种处理方法,1、在代码中增加处理部分,类似if(file.read()==null)的代码,但感觉比较麻烦。2、对不影响程序运行的异常,直接catch不处理就可以了。如下:

    def open(self):
        strFilter="document file(*.docx);;text file(*.txt)"
        fileName,_=QFileDialog.getOpenFileName(self,'选择要打开的文件','c:\\',strFilter,"document file(*.docx)")
        if(fileName.endswith("txt")):
            try:
                file=QFile()
                file.setFileName(fileName)
                strText=str()
                if(file.open(QFile.ReadOnly|QFile.Text)):
                    input=QTextStream(file)
                    strText=input.readAll()
                print(strText)
                self.textEdit.setText(strText)
            except Exception:
                None
        else:
            try:
                strText=""
                document = Document(fileName)
                for paragraph in document.paragraphs:
                    strText+=paragraph.text
                print(strText)
                self.textEdit.setText(strText)
            except Exception:
                None

这样就算不打开文件关闭对话框也就ok了。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

returnadsss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值