Source code for ui

'''
Miscellaneous user interface utilities for selecting files or directories.
If nothing or a non-existing file/direcoty is selected, the return is "0". 
Otherwise the file/directory is returned.
'''

'''
ThH, Oct 2013
Ver 2.0
'''


import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import os

[docs]def getfile(FilterSpec='*', DialogTitle='Select File: ', DefaultName='.'): ''' Selecting an existing file. Parameters ---------- FilterSpec : query-string File filters DialogTitle : string Window title DefaultName : string Can be a directory AND filename Returns ------- filename : string selected existing file pathname: string selected path Examples -------- >>> (myFile, myPath) = thLib.ui.getfile('*.py', 'Testing file-selection', 'c:\\temp\\test.py') ''' app = QApplication(sys.argv) form = QFileDialog() fullInFile = str(form.getOpenFileName(form, DialogTitle, DefaultName, FilterSpec)) app.closingDown() if not os.path.exists(fullInFile): return 0 else: print('Selection: ' + fullInFile) dirName = os.path.dirname(fullInFile) fileName = os.path.basename(fullInFile) return (fileName, dirName)
[docs]def savefile(FilterSpec='*',DialogTitle='Save File: ', DefaultName='.'): ''' Selecting an existing or new file: Parameters ---------- FilterSpec : string File filters. DialogTitle : string Window title. DefaultName : string Can be a directory AND filename. Returns ------- filename : string Selected file. pathname : string Selecte path. Examples -------- >>> (myFile, myPath) = thLib.ui.savefile('*.py', 'Testing file-selection', 'c:\\temp\\test.py') ''' app = QApplication(sys.argv) form = QFileDialog() fullOutFile = str(form.getSaveFileName(form, DialogTitle, DefaultName, FilterSpec)) app.closingDown() print('Selection: ' + fullOutFile) dirName = os.path.dirname(fullOutFile) fileName = os.path.basename(fullOutFile) return (fileName, dirName)
[docs]def getdir(DialogTitle='Select Directory', DefaultName='.'): ''' Select a directory Parameters ---------- DialogTitle : string Window title DefaultName : string Can be a directory AND filename Returns ------- directory : string Selected directory. Examples -------- >>> myDir = thLib.ui.getdir('c:\\temp', 'Pick your directory') ''' app = QApplication(sys.argv) form = QFileDialog() fullDir = str(form.getExistingDirectory(form, DialogTitle, DefaultName)) if not os.path.exists(fullDir): return 0 else: print('Selection: ' + fullDir) return fullDir
if __name__ == "__main__": # Test functions (myFile, myPath) = getfile('*.eps', 'Testing file-selection', r'c:\temp\test.eps') if myFile > 0: print('File: %s, Path: %s' % (myFile, myPath)) else: print(0) (myFile, myPath) = savefile('*.txt', 'Testing saving-selection', r'c:\temp\test.txt') myDir = getdir() print(myDir)