def saveBox(
self,
title=None,
fileName=None,
dirName=None,
fileExt=".txt",
fileTypes=None,
asFile=False):
self.topLevel.update_idletasks()
if fileTypes is None:
fileTypes = [('all files', '.*'), ('text files', '.txt')]
# define options for opening
options = {}
options['defaultextension'] = fileExt
options['filetypes'] = fileTypes
options['initialdir'] = dirName
options['initialfile'] = fileName
options['title'] = title
if asFile:
return filedialog.asksaveasfile(mode='w', **options)
# will return "" if cancelled
else:
return filedialog.asksaveasfilename(**options)
python类asksaveasfilename()的实例源码
def IDT_group2svg(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
svg_filename = tkFileDialog.asksaveasfilename(title='SVG export filename',defaultextension = 'svg',initialdir = IDT_group_dir);
plt_bnds = [0,8000,0,8000]
x0 = 40e-3
y0 = 40e-3
factor = 1e5
fig, ax = plt.subplots()
for polygon in IDT_group['final_IDT']:
polygon = shapely_affinity.translate(polygon, xoff=x0, yoff=y0)
polygon = shapely_affinity.scale(polygon, xfact = factor, yfact= factor, origin=(0,0,0))
patch = PolygonPatch(polygon, fc=BLACK, ec=None, alpha=1.0, zorder=2)
ax.add_patch(patch)
for IDT_data in IDT_group['IDT']:
reticule = IDT_data['reticule']
for polygon in reticule:
polygon = shapely_affinity.translate(polygon, xoff=x0, yoff=y0)
polygon = shapely_affinity.scale(polygon, xfact = factor, yfact= factor, origin=(0,0,0))
patch = PolygonPatch(polygon, fc=BLACK, ec='none', alpha=1.0, zorder=2)
ax.add_patch(patch)
ax.axis(plt_bnds)
ax.set_aspect(1)
#plt.show()
fig.savefig(svg_filename, format='svg', dpi=1200)
def saveBox(
self,
title=None,
fileName=None,
dirName=None,
fileExt=".txt",
fileTypes=None,
asFile=False):
self.topLevel.update_idletasks()
if fileTypes is None:
fileTypes = [('all files', '.*'), ('text files', '.txt')]
# define options for opening
options = {}
options['defaultextension'] = fileExt
options['filetypes'] = fileTypes
options['initialdir'] = dirName
options['initialfile'] = fileName
options['title'] = title
if asFile:
return filedialog.asksaveasfile(mode='w', **options)
# will return "" if cancelled
else:
return filedialog.asksaveasfilename(**options)
def _save_crop(self):
log.debug('crop bounds: %s', self._bounds)
if self._bounds is None:
return
bounds = self.select_bounds
# ext = '.%dx%d.png' % tuple(self._size)
# tkFileDialog doc: http://tkinter.unpythonic.net/wiki/tkFileDialog
save_to = tkFileDialog.asksaveasfilename(**dict(
initialdir=self._save_parent_dir,
defaultextension=".png",
filetypes=[('PNG', ".png")],
title='Select file'))
if not save_to:
return
save_to = self._fix_path(save_to)
# force change extention with info (resolution and offset)
save_to = os.path.splitext(save_to)[0] + self._fileext_text.get()
self._save_parent_dir = os.path.dirname(save_to)
log.info('Crop save to: %s', save_to)
self._image.crop(bounds).save(save_to)
self._genfile_name.set(os.path.basename(save_to))
self._gencode_text.set('d.click_image(r"%s")' % save_to)
def _save_crop(self):
log.debug('crop bounds: %s', self._bounds)
if self._bounds is None:
return
bounds = self.select_bounds
# ext = '.%dx%d.png' % tuple(self._size)
# tkFileDialog doc: http://tkinter.unpythonic.net/wiki/tkFileDialog
save_to = tkFileDialog.asksaveasfilename(**dict(
initialdir=self._save_parent_dir,
defaultextension=".png",
filetypes=[('PNG', ".png")],
title='Select file'))
if not save_to:
return
save_to = self._fix_path(save_to)
# force change extention with info (resolution and offset)
save_to = os.path.splitext(save_to)[0] + self._fileext_text.get()
self._save_parent_dir = os.path.dirname(save_to)
log.info('Crop save to: %s', save_to)
self._image.crop(bounds).save(save_to)
self._genfile_name.set(os.path.basename(save_to))
self._gencode_text.set('d.click_image(r"%s")' % save_to)
def Save_As(self, app, pad):
"""
saves the contents in pad to file
to specified filename
"""
save_file = asksaveasfilename(parent=app)
data = pad.get('1.0', GUI.END)[:-1]
f = open(save_file, 'w')
f.write(data)
f.close()
x = save_file
if platform.system() == 'Windows':
x = x.replace('/', '\\')
File.filename(map(str, x.split('\\'))[-1])
else:
pass
File.filepath(x)
app.title(File.name)
def save_selection(self, mode="selection"):
"""
Save selection in a single file.
"""
# Builds the selection.
selection = None
if mode == "selection":
selection = self.get_selected_sequences()
elif mode == "all":
selection = self.get_all_sequences()
# Ask users if they want to include indels in the sequences to save.
remove_indels_choice = False
for e in selection:
if "-" in e.my_sequence:
remove_indels_choice = tkMessageBox.askyesno(message="Would you like to remove indels from the sequences when saving them to a file?", title="Save Selection", parent=self.main_window)
break
# Ask users to chose a directory where to save the files.
filepath=asksaveasfilename(filetypes=[("fasta","*.fasta")],parent=self.main_window)
if not filepath == "":
dirpath = os.path.dirname(filepath)
filename = os.path.splitext(os.path.basename(filepath))[0]
self.build_sequences_file(selection, filename, file_format="fasta", remove_indels=remove_indels_choice, use_structural_information=False, new_directory=dirpath)
def saveBox(
self,
title=None,
fileName=None,
dirName=None,
fileExt=".txt",
fileTypes=None,
asFile=False):
self.topLevel.update_idletasks()
if fileTypes is None:
fileTypes = [('all files', '.*'), ('text files', '.txt')]
# define options for opening
options = {}
options['defaultextension'] = fileExt
options['filetypes'] = fileTypes
options['initialdir'] = dirName
options['initialfile'] = fileName
options['title'] = title
if asFile:
return filedialog.asksaveasfile(mode='w', **options)
# will return "" if cancelled
else:
return filedialog.asksaveasfilename(**options)
def action_inject(self):
"""Inject metadata into a new save file."""
split_filename = os.path.splitext(ntpath.basename(self.in_file))
base_filename = split_filename[0]
extension = split_filename[1]
self.save_options["initialfile"] = (base_filename
+ "_injected" + extension)
self.save_file = tkFileDialog.asksaveasfilename(**self.save_options)
if not self.save_file:
return
self.set_message("Saving file to %s" % ntpath.basename(self.save_file))
# Launch injection on a separate thread after disabling buttons.
self.disable_state()
self.master.after(100, self.action_inject_delay)
def save_grammar(self, *args):
filename = asksaveasfilename(filetypes=self.GRAMMAR_FILE_TYPES,
defaultextension='.cfg')
if not filename: return
try:
if filename.endswith('.pickle'):
pickle.dump((self._chart, self._tokens), open(filename, 'w'))
else:
file = open(filename, 'w')
prods = self._grammar.productions()
start = [p for p in prods if p.lhs() == self._grammar.start()]
rest = [p for p in prods if p.lhs() != self._grammar.start()]
for prod in start: file.write('%s\n' % prod)
for prod in rest: file.write('%s\n' % prod)
file.close()
except Exception, e:
tkMessageBox.showerror('Error Saving Grammar',
'Unable to open file: %r' % filename)
def print_to_file(self, filename=None):
"""
Print the contents of this C{CanvasFrame} to a postscript
file. If no filename is given, then prompt the user for one.
@param filename: The name of the file to print the tree to.
@type filename: C{string}
@rtype: C{None}
"""
if filename is None:
from tkFileDialog import asksaveasfilename
ftypes = [('Postscript files', '.ps'),
('All files', '*')]
filename = asksaveasfilename(filetypes=ftypes,
defaultextension='.ps')
if not filename: return
(x0, y0, w, h) = self.scrollregion()
self._canvas.postscript(file=filename, x=x0, y=y0,
width=w+2, height=h+2,
pagewidth=w+2, # points = 1/72 inch
pageheight=h+2, # points = 1/72 inch
pagex=0, pagey=0)
def save_grammar(self, *args):
filename = asksaveasfilename(filetypes=self.GRAMMAR_FILE_TYPES,
defaultextension='.cfg')
if not filename: return
try:
if filename.endswith('.pickle'):
pickle.dump((self._chart, self._tokens), open(filename, 'w'))
else:
file = open(filename, 'w')
prods = self._grammar.productions()
start = [p for p in prods if p.lhs() == self._grammar.start()]
rest = [p for p in prods if p.lhs() != self._grammar.start()]
for prod in start: file.write('%s\n' % prod)
for prod in rest: file.write('%s\n' % prod)
file.close()
except Exception, e:
tkMessageBox.showerror('Error Saving Grammar',
'Unable to open file: %r' % filename)
def print_to_file(self, filename=None):
"""
Print the contents of this C{CanvasFrame} to a postscript
file. If no filename is given, then prompt the user for one.
@param filename: The name of the file to print the tree to.
@type filename: C{string}
@rtype: C{None}
"""
if filename is None:
from tkFileDialog import asksaveasfilename
ftypes = [('Postscript files', '.ps'),
('All files', '*')]
filename = asksaveasfilename(filetypes=ftypes,
defaultextension='.ps')
if not filename: return
(x0, y0, w, h) = self.scrollregion()
self._canvas.postscript(file=filename, x=x0, y=y0,
width=w+2, height=h+2,
pagewidth=w+2, # points = 1/72 inch
pageheight=h+2, # points = 1/72 inch
pagex=0, pagey=0)
def save_grammar(self, *args):
filename = asksaveasfilename(filetypes=self.GRAMMAR_FILE_TYPES,
defaultextension='.cfg')
if not filename: return
try:
if filename.endswith('.pickle'):
pickle.dump((self._chart, self._tokens), open(filename, 'w'))
else:
file = open(filename, 'w')
prods = self._grammar.productions()
start = [p for p in prods if p.lhs() == self._grammar.start()]
rest = [p for p in prods if p.lhs() != self._grammar.start()]
for prod in start: file.write('%s\n' % prod)
for prod in rest: file.write('%s\n' % prod)
file.close()
except Exception, e:
tkMessageBox.showerror('Error Saving Grammar',
'Unable to open file: %r' % filename)
def print_to_file(self, filename=None):
"""
Print the contents of this C{CanvasFrame} to a postscript
file. If no filename is given, then prompt the user for one.
@param filename: The name of the file to print the tree to.
@type filename: C{string}
@rtype: C{None}
"""
if filename is None:
from tkFileDialog import asksaveasfilename
ftypes = [('Postscript files', '.ps'),
('All files', '*')]
filename = asksaveasfilename(filetypes=ftypes,
defaultextension='.ps')
if not filename: return
(x0, y0, w, h) = self.scrollregion()
self._canvas.postscript(file=filename, x=x0, y=y0,
width=w+2, height=h+2,
pagewidth=w+2, # points = 1/72 inch
pageheight=h+2, # points = 1/72 inch
pagex=0, pagey=0)
def save_sigma_file():
"""Brings up a file dialog box, so the user can choose a
file for saving the current SIGMA diagram. Then converts
the diagram to XML and saves it."""
import tkFileDialog
savefile = tkFileDialog.asksaveasfilename(
filetypes=[("SIGMA Diagram files", ".igm")],
defaultextension=".igm")
if savefile:
dom = makeSigmaDOM()
try:
f = open(savefile, "w")
dom.writexml(f)
f.close()
#global DIRTY; DIRTY = False
except:
print "Couldn't write the file: ", savefile
raise
def onSave(self):
filename = asksaveasfilename()
if filename:
alltext = self.gettext()
open(filename, 'w').write(alltext)
def browseForFile(TkStringVar):
TkStringVar.set(tkFileDialog.asksaveasfilename())
# Tkinter doesn't let you send arguments to functions, so we must make wrapper functions:
def save():
output1 = textbox.get(1.0, END)
str(output1)
filename = tkFileDialog.asksaveasfilename()
fileit = open(filename, "w")
fileit.write(output1)
def saveit():
try:
output1 = textbox.get(1.0, END)
str(output1)
filename = tkFileDialog.asksaveasfilename()
entry2.insert(END, filename)
fileit = open(filename, "w")
fileit.write(output1)
except:
textbox.insert(END, "Failed Saving Data\n")
def setOutputFile(self):
self.outputfile = tkFileDialog.asksaveasfilename()
self.browseButtonText.set(self.outputfile)
def _save_screenshot(self):
save_to = tkFileDialog.asksaveasfilename(**dict(
defaultextension=".png",
filetypes=[('PNG', '.png')],
title='Select file'))
if not save_to:
return
log.info('Save to: %s', save_to)
self._image.save(save_to)
def on_click_save_tads(self, event):
tk.Tk().withdraw() # Close the root window
save_path = filedialog.asksaveasfilename()
if save_path is not None:
with open(save_path, 'w') as o:
for region in self.tad_regions:
o.write("%s\t%d\t%d\n" % (region.chromosome, region.start-1, region.end))
def on_click_save_vector(self, event):
tk.Tk().withdraw() # Close the root window
save_path = filedialog.asksaveasfilename()
if save_path is not None:
da_sub = self.da[self.current_da_ix]
with open(save_path, 'w') as o:
for i, region in enumerate(self.regions):
o.write("%s\t%d\t%d\t.\t%e\n" % (region.chromosome, region.start-1, region.end, da_sub[i]))
def on_click_save_matrix(self, event):
tk.Tk().withdraw() # Close the root window
save_path = filedialog.asksaveasfilename()
if save_path is not None:
with open(save_path, 'w') as o:
# write regions
for i, region in enumerate(self.regions):
o.write("%s:%d-%d" % (region.chromosome, region.start-1, region.end))
if i < len(self.regions)-1:
o.write("\t")
else:
o.write("\n")
# write matrix
n_rows = self.da.shape[0]
n_cols = self.da.shape[1]
for i in range(n_rows):
window_size = self.ws[i]
o.write("%d\t" % window_size)
for j in range(n_cols):
o.write("%e" % self.da[i, j])
if j < n_cols-1:
o.write("\t")
else:
o.write("\n")
def save_as_ps(self,e=None):
filename = tkFileDialog.asksaveasfilename(parent=self.parent,title='Choose a filename',filetypes = [('Postscript', '.ps')],initialfile=self.graph_mode.get()+' graph.ps')
self.chart.postscript(file=filename, colormode='color')
def save_as_ps(self,e=None):
filename = tkFileDialog.asksaveasfilename(parent=self.parent,title='Choose a filename',filetypes = [('Postscript', '.ps')],initialfile='variation_move'+str(self.move)+'.ps')
self.goban.postscript(file=filename, colormode='color')
def save_left_as_ps(self,e=None):
filename = tkFileDialog.asksaveasfilename(parent=self.parent,title='Choose a filename',filetypes = [('Postscript', '.ps')],initialfile='move'+str(self.current_move)+'.ps')
self.goban1.postscript(file=filename, colormode='color')
def save_right_as_ps(self,e=None):
filename = tkFileDialog.asksaveasfilename(parent=self.parent,title='Choose a filename',filetypes = [('Postscript', '.ps')],initialfile='move'+str(self.current_move)+'.ps')
self.goban2.postscript(file=filename, colormode='color')
def _get_output_filename(self, title='Select Output File'):
root, _, asksaveasfilename = self._setup_tkinter()
# show an "Open" dialog box and return the path to the selected file
output_file = asksaveasfilename(title=title)
root.destroy() # Destroy the GUI
return output_file