gpt4 book ai didi

python - 选择目录后,QtGui.QFileDialog.getExistingDirectory() 窗口不会关闭(PyQt)

转载 作者:行者123 更新时间:2023-12-01 05:55:17 25 4
gpt4 key购买 nike

我正在尝试在python程序中使用QtGui.QFileDialog.getExistingDirectory()对话框窗口获取路径,以简化用户的操作,而其余的则程序在控制台输出中。我有这段代码用于此目的:

import sys, os
from PyQt4 import QtGui

def getpath(filename,
noPathFileMsg='',
wrongFolderMsg='',
selectFolderMsg=''):

try:
f = open('./'+filename,'r')
except IOError:
folder = get_new_path(filename,
noPathFileMsg,
selectFolderMsg)
else:
folder = f.readline()
f.close()
currentDir = os.getcwd()
try:
os.chdir(folder)
except:
folder = get_new_path(filename,
wrongFolderMsg,
selectFolderMsg)
else:
os.chdir(currentDir)
finally:
return folder

def get_new_path(filename,
infoMsg,
selectFolderMsg):

app = QtGui.QApplication(sys.argv)
QtGui.QMessageBox.about(None, 'No folder', infoMsg)
folder = QtGui.QFileDialog.getExistingDirectory(None, selectFolderMsg)
app.exit()
if os.name == 'posix':
folder += '/'
elif os.name == 'nt':
folder += '\\'
g = open('./'+filename,'w')
g.write(folder)
g.close()
return folder
if __name__ == '__main__':
folderPath = getpath('pathtofolder.txt',
noPathFileMsg='The path to the folder has not been set',
wrongFolderMsg='The path folder saved cannot be reached',
selectFolderMsg='Please select a folder')
print folderPath
var = input('The program stopped at the input instruction, the dialog window should now be closed!')

如果我调用 getpath 函数,对话框窗口将保持打开状态,直到调用该函数的脚本结束,而不是在此指令之后立即关闭:

folder = QtGui.QFileDialog.getExistingDirectory(None, selectFolderMsg)

如果运行此代码,它将创建一个文件,该文件将对话框窗口保存的目录保存在运行脚本的文件夹中。

我做错了什么?

顺便说一句,我使用的是 Ubuntu 12.04。谢谢你!干杯

最佳答案

在虚拟机中设置 Ubuntu 12.04 后,我可以确认单击“打开”后该对话框没有正确关闭。

该问题似乎是由于尝试退出 get_new_path 函数内的 QApplication 引起的。

相反,您应该创建一个全局 QApplication 对象,并且仅在脚本完成时退出它:

def get_new_path(filename, infoMsg, selectFolderMsg):

QtGui.QMessageBox.about(None, 'No folder', infoMsg)
folder = QtGui.QFileDialog.getExistingDirectory(None, selectFolderMsg)
...

if __name__ == '__main__':

app = QtGui.QApplication(sys.argv)

folderPath = getpath(...)

app.exit()

关于python - 选择目录后,QtGui.QFileDialog.getExistingDirectory() 窗口不会关闭(PyQt),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12860040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com