File Browser with PySide2: get the path of the file and then kill the GUI

∥☆過路亽.° 提交于 2020-04-18 05:36:06

问题


I have the following code and want to do the following:

  • Most important point: Once I clicked on the file and get its filepath, I want the GUI to quit because I would then just feed that path to another script (another_script) which I would then import

My problems is that, after the script successfully prints the path of the selected file, the GUI does not kill itself and i cannot run another_script and I'm stuck in the terminal

import sys
from PySide2.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog
from PySide2.QtGui import QIcon

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):

        self.openFileNameDialog()

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        fileName, _ = QFileDialog.getOpenFileName(self,
            "QFileDialog.getOpenFileName()", 
            "","All Files (*);;Python Files (*.py)", 
            options=options)
        if fileName:
            print(fileName)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
import another_script

回答1:


Even though you have selected the file the event loop will still continue to run, a possible solution is to call QXApplication.quit() with a QTimer but there is still a problem: that method will make the exec_() method return 0 which is taken by sys.exit() and consequently the application will be closed. But all of the above is unnecessary since if you just want to get the path of a file then you don't need to use a QWidget, you can use the following:

import sys
from PySide2.QtWidgets import QApplication, QFileDialog


def get_filename():
    app = QApplication([])
    options = QFileDialog.Options()
    options |= QFileDialog.DontUseNativeDialog
    fileName, _ = QFileDialog.getOpenFileName(
        None,
        "QFileDialog.getOpenFileName()",
        "",
        "All Files (*);;Python Files (*.py)",
        options=options,
    )
    return fileName


if __name__ == "__main__":
    filename = get_filename()
    if filename:
        print(filename)


来源:https://stackoverflow.com/questions/60977801/file-browser-with-pyside2-get-the-path-of-the-file-and-then-kill-the-gui

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