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



我正试图在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()

最新更新