我正在尝试在程序中获取带有QtGui.QFileDialog.getExistingDirectory()
对话框窗口的路径,以便在python
程序的其余部分在控制台输出中时为用户简化操作。为此,我有这段代码:
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 上。谢谢!干杯