def _setup_tkinter(self):
'''Creates a Tkinter input file dialog'''
# Import Tkinter GUI widgets
if sys.version_info.major == 2:
from tkFileDialog import askopenfilename, asksaveasfilename
import Tkinter as tk
else:
from tkinter.filedialog import askopenfilename, asksaveasfilename
import tkinter as tk
# Code below is to make sure the file dialog appears above the
# terminal/browser
# Based on
# http://stackoverflow.com/questions/3375227/how-to-give-tkinter-file-dialog-focus
# Make a top-level instance and hide since it is ugly and big.
root = tk.Tk()
root.withdraw()
# Make it almost invisible - no decorations, 0 size, top left corner.
root.overrideredirect(True)
root.geometry('0x0+0+0')
# Show window again and lift it to top so it can get focus,
# otherwise dialogs will end up behind the terminal.
root.deiconify()
root.lift()
root.focus_force()
return root, askopenfilename, asksaveasfilename
python类asksaveasfilename()的实例源码
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 IDTgroup2svg(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='Wafer routing filename',defaultextension = 'svg',initialdir = IDT_group_dir);
svg_dwg = SVGT.Init_svg(svg_filename)
for IDT_data in IDT_group['IDT']:
IDT2svg(IDT_data,svg_dwg)
svg_dwg.save();
IDT_group['svg_route']=svg_filename
def IDT_group2gds(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
gds_filename = tkFileDialog.asksaveasfilename(title='Wafer gds filename',defaultextension = 'gds',initialdir = IDT_group_dir);
layout = gds.core.Layout('LIBRARY')
cell = gds.core.Cell('Main')
for polygon in IDT_group['final_IDT']:
points_exterior = 1e6*array(polygon.exterior.coords) #best practice: dimensions in um
points_interior_has_to_be_created = True
for interior_ring in polygon.interiors:
if points_interior_has_to_be_created:
points_interior = 1e6*array(interior_ring.coords)
points_interior_has_to_be_created = False
else:
points_interior = vstack((points_interior,1e6*array(interior_ring.coords)))
if not polygon.interiors:
boundaries = gds.core.Boundary(points_exterior)
else:
boundaries = gds.core.Boundary(vstack((points_interior,points_exterior)))
cell.add(boundaries)
for IDT_data in IDT_group['IDT']:
reticule = IDT_data['reticule']
for polygon in reticule:
points = 1e6*array(polygon.exterior.coords)
boundaries = gds.core.Boundary(points)
cell.add(boundaries)
layout.add(cell)
layout.save(gds_filename)
def export_models(self):
if self._check_run():
filename = tkfile.asksaveasfilename(title = "Export models",
filetypes = [ ("Pickle", ".pickle") ],
defaultextension = ".pickle")
if len(filename) > 0:
with open(filename, "wb") as f:
pickle.dump(self.solver.models, f, protocol = pickle.HIGHEST_PROTOCOL)
def export_fitness(self):
if self._check_run():
filename = tkfile.asksaveasfilename(title = "Export fitness",
filetypes = [ ("Pickle", ".pickle") ],
defaultextension = ".pickle")
if len(filename) > 0:
with open(filename, "wb") as f:
pickle.dump(self.solver.energy, f, protocol = pickle.HIGHEST_PROTOCOL)
def save_as(self, path=None):
if path:
return motion_plan.dump(path)
if motion_plan.path:
initialdir, initialfile = os.path.split(motion_plan.path)
path = tkFileDialog.asksaveasfilename(
parent=self.master, initialfile=initialfile,
initialdir=initialdir)
else:
path = tkFileDialog.asksaveasfilename(parent=self.master)
if path:
motion_plan.dump(path)
def Get_Save_File(self):
if self.load_filename==None:
showwarning("Export G-Code", "Nothing to export!")
return
myFormats = [('G-Code for EMC2','*.ngc'),\
('All File','*.*') ]
(beg, ende)=os.path.split(self.load_filename)
(fileBaseName, fileExtension)=os.path.splitext(ende)
inidir=self.config.save_path
self.save_filename = asksaveasfilename(initialdir=inidir,\
initialfile=fileBaseName +'.ngc',filetypes=myFormats)
def Get_Save_File(self):
if self.load_filename==None:
showwarning("Export G-Code", "Nothing to export!")
return
myFormats = [('G-Code for EMC2','*.ngc'),\
('All File','*.*') ]
(beg, ende)=os.path.split(self.load_filename)
(fileBaseName, fileExtension)=os.path.splitext(ende)
inidir=self.config.save_path
self.save_filename = asksaveasfilename(initialdir=inidir,\
initialfile=fileBaseName +'.ngc',filetypes=myFormats)
def save(self, editor):
if not editor.f:
fpathname = asksaveasfilename()
if not fpathname:
# file not saved
return False
editor.open(fpathname)
self.write(editor=editor)
# file saved
return True
def filesavebox(msg=None
, title=None
, default=""
, filetypes=None
):
"""
A file to get the name of a file to save.
Returns the name of a file, or None if user chose to cancel.
The "default" argument should contain a filename (i.e. the
current name of the file to be saved). It may also be empty,
or contain a filemask that includes wildcards.
The "filetypes" argument works like the "filetypes" argument to
fileopenbox.
"""
boxRoot = Tk()
boxRoot.withdraw()
initialbase, initialfile, initialdir, filetypes = fileboxSetup(default,filetypes)
f = tk_FileDialog.asksaveasfilename(parent=boxRoot
, title=getFileDialogTitle(msg,title)
, initialfile=initialfile
, initialdir=initialdir
, filetypes=filetypes
)
boxRoot.destroy()
if not f: return None
return os.path.normpath(f)
#-------------------------------------------------------------------
#
# fileboxSetup
#
#-------------------------------------------------------------------
def export_data(self):
if self.canvas_plot.plots_list != []:
filepath = tkFileDialog.asksaveasfilename(filetypes=[("csv","*.csv")],parent=self)
if not filepath == "":
try:
output_file_handler = open(filepath,"w")
print >> output_file_handler, self.canvas_plot.export_to_csv()
output_file_handler.close()
except:
pass
else:
tkMessageBox.showerror("Export Error", "No data to export.", parent=self)
def save_postscript(self):
filepath = tkFileDialog.asksaveasfilename(filetypes=[("ps","*.ps")],parent=self)
if not filepath == "":
try:
# Lowers the stack level of the points in order to hide them in the .ps image.
self.canvas_plot.tag_lower("type:point")
self.canvas_plot.postscript(file=filepath, colormode='color')
self.canvas_plot.set_canvas_stack()
except:
pass
def save_new_project_from_main_menu(self):
save_project_full_path = asksaveasfilename(defaultextension="", filetypes=pmdt.pymod_session_extension, parent=self.main_window)
if save_project_full_path == "":
return None
self.save_pymod_project(save_project_full_path)
def sequence_save(self, element):
"""
Save a single sequence to a file.
"""
remove_indels_choice = False
if "-" in element.my_sequence:
remove_indels_choice = tkMessageBox.askyesno(message="Would you like to remove indels from the sequence when saving it to a file?", title="Save File", parent=self.main_window)
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([element], filename, file_format="fasta", remove_indels=remove_indels_choice, use_structural_information=False, new_directory=dirpath)
def save_full_model_to_file(self, full_model):
save_file_full_path = asksaveasfilename(defaultextension = "", filetypes = [("PDB","*.pdb")], parent=pymod.main_window)
if save_file_full_path != "":
# Moves the saved file to the path chosen by the user.
try:
old_path = full_model.original_file_path
os.rename(old_path, save_file_full_path)
except:
title = "File Error"
message = "Could not save the alignment file to path: %s" % (save_file_full_path)
self.show_error_message(title, message)
def GetOutputPath():
filename_SaveFile = tkFileDialog.asksaveasfilename(initialdir="C:\\", title="Select Output File Path",
filetypes=(("dat files", "*dat"), ("all files", "*.*")))
ent_OutputFile.insert(0, filename_SaveFile)
# Function to print status updates to the text area
def export_to_batch(self):
outf = filedialog.asksaveasfilename(defaultextension='.txt')
if outf:
with open(outf,'w') as f:
for i in self.download_list:
f.write(i[1].strip()+'\n')
message.showinfo('Complete','Done exporting batch job to file')
def handleSaveAs(*args):
global fname
name=tkFileDialog.asksaveasfilename(initialfile=fname, filetypes=[('text', '.txt')])
if(name):
if(name!=fname):
with open(name, 'w') as f:
fname=name
f.write(editBox.get(START, END).encode('utf8', 'replace'))
top.wm_title("Constrained Writer: "+fname)
def save(self):
print('Save selected')
outputFile = asksaveasfilename(defaultextension='.jpg')
if outputFile is not None:
outputImage = Image.new('RGB', (self.model.getWidth(), self.model.getHeight()))
for region in self.model.getRegions():
imageFile = self.model.regionToImageFile[region]
if imageFile is None:
print('Warning: Region without image {0}'.format(region))
continue
image = imageFile.getImageObject((region[2], region[3]), 'export')
outputImage.paste(image, (region[0], region[1]))
outputImage.save(outputFile)