def choose_path(self):
"""
Called when users press the 'Browse' button in order to choose a path on their system.
"""
current_path = self.getvalue()
new_path = None
# Lets users choose a new path.
if self.path_type == "file":
new_path = askopenfilename(title = self.askpath_title,
initialdir=os.path.dirname(current_path),
initialfile=os.path.basename(current_path), parent = get_parent_window(self), filetypes = self.file_types)
elif self.path_type == "directory":
new_path = askdirectory(title = self.askpath_title, initialdir=os.path.dirname(current_path), mustexist = True, parent = get_parent_window(self))
# Updates the text in the Entry with the new path name.
if new_path:
self.clear()
self.setvalue(new_path)
if hasattr(self.run_after_selection, "__call__"):
self.run_after_selection()
python类askopenfilename()的实例源码
def openBox(
self,
title=None,
dirName=None,
fileTypes=None,
asFile=False):
self.topLevel.update_idletasks()
# define options for opening
options = {}
if title is not None:
options['title'] = title
if dirName is not None:
options['initialdir'] = dirName
if fileTypes is not None:
options['filetypes'] = fileTypes
if asFile:
return filedialog.askopenfile(mode="r", **options)
# will return "" if cancelled
else:
return filedialog.askopenfilename(**options)
def openBox(
self,
title=None,
dirName=None,
fileTypes=None,
asFile=False):
self.topLevel.update_idletasks()
# define options for opening
options = {}
if title is not None:
options['title'] = title
if dirName is not None:
options['initialdir'] = dirName
if fileTypes is not None:
options['filetypes'] = fileTypes
if asFile:
return filedialog.askopenfile(mode="r", **options)
# will return "" if cancelled
else:
return filedialog.askopenfilename(**options)
def load(self):
absfilename=tkFileDialog.askopenfilename(title="Choose an algorithm file",filetypes=[("Algorithm",("*.f90","*.F90")),("All files","*.*")])
# the parser requires us to be in the same directory. This should be fixed.
path,filename=os.path.split(absfilename)
os.chdir(path)
ast,invokeInfo=parse(filename,api="gunghoproto")
self.algtext.delete(1.0, END)
self.psy=PSyFactory("gunghoproto").create(invokeInfo)
# *************************************
# USE invoke object (or some unique text from the invoke) as the tag so each object gets its own callback?
# need to link invoke objects to line numbers (need to be provided by parser)
# hacky temporary alternative just count invokes for the moment
invokeCount=0
for line in str(ast).split("\n"):
if "invoke" in line.lower():
tag="invoke"+str(invokeCount)
self.algtext.insert(tk.INSERT, line+"\n", tag)
bind=Bind(self.algtext,tag,self.psy.invokes.invokeList[invokeCount],self.psytext,self.interact,self.c,self._canvasControl)
self.algtext.tag_bind(tag,"<Enter>", bind.entry)
self.algtext.tag_bind( tag, '<Leave>', bind.leave )
self.algtext.tag_bind( tag, '<ButtonPress-1>', bind.button )
invokeCount+=1
else:
self.algtext.insert(tk.INSERT, line+"\n")
def launch_review():
filename = tkFileDialog.askopenfilename(parent=app,title='Select a file',filetypes = [('sgf reviewed', '.rsgf')])
log(filename)
if not filename:
return
top = Toplevel()
display_factor=.5
screen_width = app.winfo_screenwidth()
screen_height = app.winfo_screenheight()
width=int(display_factor*screen_width)
height=int(display_factor*screen_height)
new_popup=dual_view.DualView(top,filename,min(width,height))
new_popup.pack(fill=BOTH,expand=1)
popups.append(new_popup)
top.mainloop()
def Import_IDT_parameters(IDT_group):
IDT_group_dir = IDT_group['IDT_group_dir']
Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
csv_filename = tkFileDialog.askopenfilename(title = 'IDT design file ?', defaultextension = 'csv',initialdir = IDT_group_dir)
slowness_database = {}
with open(csv_filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
parameters = Read_IDT_param_from_row(row)
IDT_data = {'parameters' : parameters}
IDT_data['parameters']['reticule_filename']=IDT_group_dir + '/' +parameters['reticule_filename'] + '.svg'
key =parameters['slowness_substrate']
if key not in slowness_database.keys():
try:
slowness_filename = IDT_group_dir + '/' + key + '.mat'
slowness_database[key] = Import_slowness_from_matlab_NoGui(slowness_filename)
except IOError:
slowness_database[key] = Import_slowness_from_matlab(IDT_group,query = "File %s not found" %key)
IDT_data['parameters']['slowness_substrate'] = slowness_database[key]
#CONTINUE FROM HERE (exception handling file not found)
IDT_group['IDT'].append(IDT_data)
def genDynamicCallGraph(event):
absoluteFileName = tkFileDialog.askopenfilename()
print(absoluteFileName)
fileNameTokens = absoluteFileName.split("/")
relFileName = fileNameTokens[len(fileNameTokens)-1]
outFileName = "tracer_" + relFileName[relFileName.index('_')+1:relFileName.index('.')] + ".dot"
tracerCommand = []
tracerCommand.append("python")
tracerCommand.append("./scripts/tracer.py")
tracerCommand.append(absoluteFileName)
outFile = open(outFileName, "w")
result = subprocess.call(tracerCommand, stdout=outFile)
outFile.close()
graphCommand = []
graphCommand.append("dot")
graphCommand.append("-Tpdf")
graphCommand.append("-O")
graphCommand.append(outFileName)
result = subprocess.call(graphCommand)
print(result)
subprocess.call("open " + outFileName + ".pdf", shell=True)
def genDomTree(event):
absoluteFileName = tkFileDialog.askopenfilename()
fileNameTokens = absoluteFileName.split("/")
relFileName = fileNameTokens[len(fileNameTokens)-1]
outFileName = "tracerDom_" + relFileName[relFileName.index('_')+1:relFileName.index('.')] + ".dot"
tracerDomCommand = []
tracerDomCommand.append("python")
tracerDomCommand.append("./scripts/tracerDom.py")
tracerDomCommand.append(absoluteFileName)
outFile = open(outFileName, "w")
result = subprocess.call(tracerDomCommand, stdout=outFile)
outFile.close()
graphCommand = []
graphCommand.append("dot")
graphCommand.append("-Tpdf")
graphCommand.append("-O")
graphCommand.append(outFileName)
result = subprocess.call(graphCommand)
print(result)
subprocess.call("open " + outFileName + ".pdf", shell=True)
def genFreqCallGraph(event):
absoluteFileName = tkFileDialog.askopenfilename()
print(absoluteFileName)
fileNameTokens = absoluteFileName.split("/")
relFileName = fileNameTokens[len(fileNameTokens)-1]
outFileName = "tracerFreq_" + relFileName[relFileName.index('_')+1:relFileName.index('.')] + ".dot"
tracerCommand = []
tracerCommand.append("python")
tracerCommand.append("./scripts/tracerFreq.py")
tracerCommand.append(absoluteFileName)
outFile = open(outFileName, "w")
result = subprocess.call(tracerCommand, stdout=outFile)
outFile.close()
graphCommand = []
graphCommand.append("dot")
graphCommand.append("-Tpdf")
graphCommand.append("-O")
graphCommand.append(outFileName)
result = subprocess.call(graphCommand)
print(result)
subprocess.call("open " + outFileName + ".pdf", shell=True)
def genFreqDomTree(event):
absoluteFileName = tkFileDialog.askopenfilename()
fileNameTokens = absoluteFileName.split("/")
relFileName = fileNameTokens[len(fileNameTokens)-1]
outFileName = "tracerDomFreq_" + relFileName[relFileName.index('_')+1:relFileName.index('.')] + ".dot"
tracerDomCommand = []
tracerDomCommand.append("python")
tracerDomCommand.append("./scripts/tracerDomFreq.py")
tracerDomCommand.append(absoluteFileName)
outFile = open(outFileName, "w")
result = subprocess.call(tracerDomCommand, stdout=outFile)
outFile.close()
graphCommand = []
graphCommand.append("dot")
graphCommand.append("-Tpdf")
graphCommand.append("-O")
graphCommand.append(outFileName)
result = subprocess.call(graphCommand)
print(result)
subprocess.call("open " + outFileName + ".pdf", shell=True)
def load_data_file(self):
dir_name, file_name = os.path.split(__file__)
dir_name = os.path.join(dir_name, 'examples')
file_path = askopenfilename(title='Choose .json file', initialdir=dir_name)
if file_path and os.path.isfile(file_path):
try:
_, fname = os.path.split(file_path)
with open(file_path, 'r') as fid:
data = fid.read()
self.conf_dict[file_path] = json.loads(data)
fname_sec = fname.split('.')
if len(fname_sec) > 1:
fname = '.'.join(fname_sec[:-1])
tk.Radiobutton(self.conf_frame, text=fname,
variable=self.conf_name,
value=file_path).pack(side=tk.LEFT)
self.conf_name.set(file_path)
except Exception as e:
showerror(title='Open file',
message='Unable to load json: %s' % e.message)
def onOpen(self):
ftypes = [('all files', '.*'), ('text files', '.txt'), ('ann files', '.ann')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
# file_opt = options = {}
# options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
# dlg = tkFileDialog.askopenfilename(**options)
fl = dlg.show()
if fl != '':
self.text.delete("1.0",END)
text = self.readFile(fl)
self.text.insert(END, text)
self.setNameLabel("File: " + fl)
self.autoLoadNewFile(self.fileName, "1.0")
# self.setDisplay()
# self.initAnnotate()
self.text.mark_set(INSERT, "1.0")
self.setCursorLabel(self.text.index(INSERT))
def onOpen(self):
ftypes = [('all files', '.*'), ('text files', '.txt'), ('ann files', '.ann')]
dlg = tkFileDialog.Open(self, filetypes = ftypes)
# file_opt = options = {}
# options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
# dlg = tkFileDialog.askopenfilename(**options)
fl = dlg.show()
if fl != '':
self.text.delete("1.0",END)
text = self.readFile(fl)
self.text.insert(END, text)
self.setNameLabel("File: " + fl)
self.setDisplay()
# self.initAnnotate()
self.text.mark_set(INSERT, "1.0")
self.setCursorLabel(self.text.index(INSERT))
def open_file_from_the_main_menu(self):
"""
This method is called when new sequences are loaded from the main menu.
"""
# Creates a tkinter widget that lets the user select multiple files.
try:
file_names = askopenfilename(filetypes=pmdt.supported_file_types, multiple=True, parent=self.main_window)
except: # PyMOL 2.0 fix.
file_names = askopenfilename(multiple=True, parent=self.main_window)
for single_file_name in pmos.get_askopenfilename_tuple(file_names):
extension = os.path.splitext(os.path.basename(single_file_name))[1].replace(".","")
if extension.lower() == "fasta":
if self.is_sequence_file(single_file_name, "fasta"):
self.open_sequence_file(single_file_name, "fasta")
elif extension.lower() == "gp":
if self.is_sequence_file(single_file_name, "genbank"):
self.open_sequence_file(single_file_name, "genbank")
elif extension.lower() == "pdb":
if self.is_pdb(single_file_name):
self.open_pdb_file(single_file_name)
elif extension.lower() == "ent":
if self.is_pdb(single_file_name):
self.open_pdb_file(single_file_name)
def choose_alignment_file(self):
"""
Lets users choose an alignment file.
"""
# Creates a tkinter widget that lets the user select multiple files.
openfilename = askopenfilename(filetypes=pmdt.alignment_file_formats, multiple=False,parent=self.main_window)
if openfilename == "":
return (None, None)
# Finds the right extension.
extension = os.path.splitext(os.path.basename(openfilename))[1].replace(".","") # BUG.
if extension == "fasta":
pass
elif extension == "aln":
extension = "clustal"
# Unknown format.
else:
title = "Format Error"
message = "Unkwnown alignment file format: %s" % (extension)
self.show_error_message(title,message)
return (None, None)
return openfilename, extension
def openBox(
self,
title=None,
dirName=None,
fileTypes=None,
asFile=False):
self.topLevel.update_idletasks()
# define options for opening
options = {}
if title is not None:
options['title'] = title
if dirName is not None:
options['initialdir'] = dirName
if fileTypes is not None:
options['filetypes'] = fileTypes
if asFile:
return filedialog.askopenfile(mode="r", **options)
# will return "" if cancelled
else:
return filedialog.askopenfilename(**options)
def handleOpen(*args):
global fname
name=tkFileDialog.askopenfilename(filetypes=[('text', '.txt')])
if(name):
if(name!=fname):
with open(name, 'r') as f:
fname=name
try:
editBox.delete(START, END)
except:
pass
editBox.insert(START, f.read())
top.wm_title("Constrained Writer: "+fname)
editBox.mark_set("matchStart", START)
editBox.mark_set("matchEnd", START)
handleKeyActivity()
def specialFour(event):
#points to condition 5 and gets duration and w/h to display
canvas = event.widget.canvas
try:
canvas.condition = 5
currdir = os.getcwd()
root = Tkinter.Tk()
root.withdraw()
temp = tkFileDialog.askopenfilename(parent=root, initialdir=currdir,\
title='Please select a Video File')
if len(temp) > 0:
canvas.path2 = temp
video = VideoFileClip(canvas.message)
video2 = VideoFileClip(canvas.path2)
canvas.duration = int(video.duration)
canvas.duration2 = int(video2.duration)
canvas.w = video.w
canvas.h = video.h
redrawAll(canvas)
except:
canvas.condition = 4
canvas.create_text(250,10,text='Please Try Again')
def editOne(event):
canvas = event.widget.canvas
try:
canvas.selected = 1
canvas.condition = 3
#one slider is unnecessary
canvas.end = False
#asks for file two
currdir = os.getcwd()
root = Tkinter.Tk()
root.withdraw()
temp = tkFileDialog.askopenfilename(parent=root, initialdir=currdir,\
title='Please select a Video File')
if len(temp) > 0:
canvas.path2 = temp
canvas.duration = int(VideoFileClip(canvas.message).duration)
canvas.duration2 = int(VideoFileClip(canvas.path2).duration)
canvas.end1 = int(VideoFileClip(canvas.message).duration)
canvas.end2 = int(VideoFileClip(canvas.path2).duration)
redrawAll(canvas)
except:
canvas.condition = 2
canvas.create_text(250,10,text='Please Try Again')
#initializes insert audio parameters
def editTwo(event):
canvas = event.widget.canvas
try:
canvas.selected = 2
canvas.condition = 3
canvas.end = False
currdir = os.getcwd()
root = Tkinter.Tk()
root.withdraw()
temp = tkFileDialog.askopenfilename(parent=root, initialdir=currdir,\
title='Please select a Sound File')
if len(temp) > 0:
canvas.path2 = temp
canvas.duration = int(VideoFileClip(canvas.message).duration)
canvas.duration2 = int(AudioFileClip(canvas.path2).duration)
canvas.end1 = int(VideoFileClip(canvas.message).duration)
canvas.end2 = int(AudioFileClip(canvas.path2).duration)
redrawAll(canvas)
except:
canvas.condition = 2
canvas.create_text(250,10,text='Please Try Again')
#processes word insertion
def editFour(event):
canvas = event.widget.canvas
try:
canvas.selected = 4
canvas.condition = 3
currdir = os.getcwd()
root = Tkinter.Tk()
root.withdraw()
temp = tkFileDialog.askopenfilename(parent=root, initialdir=currdir,\
title='Please select a Video File')
if len(temp) > 0:
canvas.path2 = temp
canvas.duration = int(VideoFileClip(canvas.message).duration)
canvas.duration2 = int(VideoFileClip(canvas.path2).duration)
canvas.end1 = int(VideoFileClip(canvas.message).duration)
canvas.end2 = int(VideoFileClip(canvas.path2).duration)
redrawAll(canvas)
except:
canvas.condition = 2
canvas.create_text(250,10,text='Please Try Again')
#initializes replace audio parameters
def editFive(event):
canvas = event.widget.canvas
try:
canvas.selected = 5
canvas.condition = 3
currdir = os.getcwd()
root = Tkinter.Tk()
root.withdraw()
temp = tkFileDialog.askopenfilename(parent=root, initialdir=currdir, \
title='Please select a Sound File')
if len(temp) > 0:
canvas.path2 = temp
canvas.duration = int(VideoFileClip(canvas.message).duration)
canvas.duration2 = int(AudioFileClip(canvas.path2).duration)
canvas.end1 = int(VideoFileClip(canvas.message).duration)
canvas.end2 = int(AudioFileClip(canvas.path2).duration)
redrawAll(canvas)
except:
canvas.condition = 2
canvas.create_text(250,10,text='Please Try Again')
#removes audio from clip
def askopenfilename(self):
# define options for opening or saving a file
self.file_opt = options = {}
#options['defaultextension'] = '' #'.csv'
#options['filetypes'] = [('all files', '.*'), ('text files', '.csv')]
options['initialdir'] = expanduser(self.filename) if self.filename else expanduser("~")
#options['initialfile'] = ''
options['parent'] = self
options['title'] = 'Choose File to upload'
# get filename
_filename = tkFileDialog.askopenfilename(**self.file_opt)
# open file on your own
if _filename:
self.filename = _filename
self.file_button["text"] = self.filename if (len(self.filename) <= 33) else "...{}".format(self.filename[-30:])
self.s3_name.set(ntpath.basename(self.filename))
def choosemap(self, maplist, initialdir):
p = Tkinter.Tk()
p.withdraw()
mappath = tkFileDialog.askopenfilename(
parent=p, initialdir=initialdir, title="Choose .map file",
filetypes=[("EM and SAXS shape descriptors", ".map"),
("EM and SAXS shape descriptors", ".mrc"),
("EM and SAXS shape descriptors", ".pdb"),
("EM and SAXS shape descriptors", ".ccp4")
]
)
if mappath != "" and mappath != ():
mapname = mappath.split("/")[-1]
maplist.settext("#0 "+mapname)
return mappath
def file_window(self):
file_name = askopenfilename(parent=self.root, title='????', \
filetypes=[('FEN Records', '*.fen'), ('Text Files', '*.txt'), ('All Files', '*.*')],
initialdir='Resourses/', \
initialfile='example.fen')
# self.file = open(file_name, 'r')
# self.play()
# '''
try:
self.file = open(file_name, 'r')
self.play()
except IOError:
if askokcancel('?????', '???????'):
self.file_window()
else:
self.root.destroy()
# '''
def file_window(self):
file_name = askopenfilename(parent=self.root, title='????', \
filetypes=[('FEN Records', '*.fen'), ('Text Files', '*.txt'), ('All Files', '*.*')],
initialdir='Resourses/', \
initialfile='example.fen')
# self.file = open(file_name, 'r')
# self.play()
# '''
try:
self.file = open(file_name, 'r')
self.play()
except IOError:
if askokcancel('?????', '???????'):
self.file_window()
else:
self.root.destroy()
# '''
def _load_run_results(self):
filename = filedialog.askopenfilename()
if not filename:
return
self.runresultsvar.set(filename)
valid_parsers = importer.get_parsers(filename, self.cfg)
if not valid_parsers:
messagebox.showerror(
'Unknown Format', 'Unable to parse this file. '
'View log for details.')
self.choose_parser['values'] = ['']
self.choose_parser.current(0)
self.choose_parser.event_generate('<<ComboboxSelected>>')
return
self.valid_parsers = {p.__name__: p for p in valid_parsers}
self.choose_parser['values'] = list(self.valid_parsers.keys())
if len(valid_parsers) > 1:
self.choose_parser.config(state='enabled')
self.choose_parser.current(0)
self.choose_parser.event_generate('<<ComboboxSelected>>')
def load_chart(self, *args):
"Load a chart from a pickle file"
filename = askopenfilename(filetypes=self.CHART_FILE_TYPES,
defaultextension='.pickle')
if not filename: return
try:
chart = pickle.load(open(filename, 'r'))
self._chart = chart
self._cv.update(chart)
if self._matrix: self._matrix.set_chart(chart)
if self._matrix: self._matrix.deselect_cell()
if self._results: self._results.set_chart(chart)
self._cp.set_chart(chart)
except Exception, e:
raise
tkMessageBox.showerror('Error Loading Chart',
'Unable to open file: %r' % filename)
def loadTypetoTarget(self, fileType, targetWindow, ftype = None):
if not (fileType and targetWindow): return
from tkFileDialog import askopenfilename
ftypes = [(fileType, fileType)]
filename = askopenfilename(filetypes=ftypes, defaultextension=fileType)
self.loadIntoWindow(filename, targetWindow)
# set the config menu to blank
self.configsMenuButton.configure(text='<none>')
# !!! remember to reset all the filenames as well!
if filename:
if ftype == 'l': self.lexfilename = filename
elif ftype == 'r': self.rulfilename = filename
def load_chart(self, *args):
"Load a chart from a pickle file"
filename = askopenfilename(filetypes=self.CHART_FILE_TYPES,
defaultextension='.pickle')
if not filename: return
try:
chart = pickle.load(open(filename, 'r'))
self._chart = chart
self._cv.update(chart)
if self._matrix: self._matrix.set_chart(chart)
if self._matrix: self._matrix.deselect_cell()
if self._results: self._results.set_chart(chart)
self._cp.set_chart(chart)
except Exception, e:
raise
tkMessageBox.showerror('Error Loading Chart',
'Unable to open file: %r' % filename)