pannnsy
2018-12-11 06:06
采纳率: 100%
浏览 4.8k

[PyQT5] QFileDialog窗口关闭时主窗口也关闭

新手,在尝试写一个pyqt5的小软件。

现在是要点击button后,出现QFileDialog文件对话框,打开文件或保存文件

但是debug时点击button,打开对话框,点击关掉对话框或取消选择时,整个界面都会退出,只有Process finished with exit code 1的提示

我希望关闭窗口时,主窗口不能被影响,请问哪里出错?

以下是相关代码

    def __init__(self,parent=None):

        #button clicked
        self.loadFileButton.clicked.connect(self.loadFile)
        self.generateButton.clicked.connect(self.generateFile)




    #loadFileButton 加载配置文件到textEdit
    def loadFile(self):
        path = QFileDialog.getOpenFileName(self,
                                                '加载配置文件',
                                                '',
                                                'Python (*.py)')
        f = open(path[0],'r+',encoding='UTF-8')
        with f:
            self.data = "".join(f.readlines())
            self.textEdit.setText(self.data)

    #generateButton 保存配置文件
    def generateFile(self):
        self.data = self.textEdit.toPlainText()
        path = QFileDialog.getSaveFileName(self,
                                               "保存配置文件",
                                               '',
                                               'Python (*.py)')
        with open(path[0],'w',encoding='UTF-8') as f:
            f.write(self.data)
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • lyhsdy 2018-12-11 06:23
    已采纳

    你试试path = QFileDialog.getOpenFileName(filter='Python (*.py)')

    如果不行,你试下try来检查错误,不会直接退出

    def loadFile(self):
            try:
                        path = QFileDialog.getOpenFileName(filter='Python (*.py)')
                        f = open(path[0],'r+',encoding='UTF-8')
                        with f:
                                self.data = "".join(f.readlines())
                                self.textEdit.setText(self.data)
            except Exception as e:
               print(e)
    

    这样就应该不会报错了

    path = QFileDialog.getOpenFileName(filter='Python (*.py)')
    if path!="":
        f = open(path[0],'r+',encoding='UTF-8')
        with f:
            self.data = "".join(f.readlines())
            self.textEdit.setText(self.data)
    
    打赏 评论
  • pannnsy 2018-12-12 06:06

    楼上是OK的,不过其实要把path变成str之后,if语句才有效,因为QFileDialog.getOpenFileName返回的是tuple(filename, filters)

    代码如下

        def loadFile(self):
            path,_ = QFileDialog.getOpenFileName(self,"加载配置文件",'','Python (*.py)')
            if path == '':
                pass
            else:
                f = open(path, 'r+', encoding='UTF-8')
                with f:
                    self.data = "".join(f.readlines())
                    self.textEdit.setText(self.data)
    
    
    4 打赏 评论

相关推荐 更多相似问题