带有 PySide2 的文件浏览器:获取文件的路径,然后杀死 GUI [英] File Browser with PySide2: get the path of the file and then kill the GUI
问题描述
我有以下代码并希望执行以下操作:
I have the following code and want to do the following:
- 最重要的一点:一旦我单击文件并获取其文件路径,我希望 GUI 退出,因为我只需将该路径提供给另一个脚本 (
another_script
),然后我将导入该脚本
- 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
我的问题是,在脚本成功打印所选文件的路径后,GUI 不会自行终止,我无法运行 another_script
并且卡在终端中
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
推荐答案
即使您选择了文件,事件循环仍将继续运行,一个可能的解决方案是使用 QTimer 调用 QXApplication.quit() 但有仍然是一个问题:该方法将使 exec_() 方法返回 0,该方法由 sys.exit() 获取,因此应用程序将被关闭.但以上所有都是不必要的,因为如果您只想获取文件的路径,那么您不需要使用 QWidget,您可以使用以下内容:
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)
这篇关于带有 PySide2 的文件浏览器:获取文件的路径,然后杀死 GUI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!