Python tkFileDialog.asksaveasfilename() Examples
The following are 30
code examples of tkFileDialog.asksaveasfilename().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
tkFileDialog
, or try the search function
.
Example #1
Source File: gui.py From snn_toolbox with MIT License | 9 votes |
def save_settings(self): """Save current settings.""" s = {key: self.settings[key].get() for key in self.settings} if self.store_last_settings: if not os.path.exists(self.default_path_to_pref): os.makedirs(self.default_path_to_pref) with open(os.path.join(self.default_path_to_pref, '_last_settings.json'), 'w') as f: f.write(json.dumps(s)) self.store_last_settings = False else: path_to_pref = filedialog.asksaveasfilename( defaultextension='.json', filetypes=[("json files", '*.json')], initialdir=self.default_path_to_pref, title="Choose filename") with open(path_to_pref, 'w') as f: f.write(json.dumps(s))
Example #2
Source File: EDMarketConnector.py From EDMarketConnector with GNU General Public License v2.0 | 7 votes |
def save_raw(self): self.status['text'] = _('Fetching data...') self.w.update_idletasks() try: data = companion.session.station() self.status['text'] = '' f = tkFileDialog.asksaveasfilename(parent = self.w, defaultextension = platform=='darwin' and '.json' or '', filetypes = [('JSON', '.json'), ('All Files', '*')], initialdir = config.get('outdir'), initialfile = '%s%s.%s.json' % (data.get('lastSystem', {}).get('name', 'Unknown'), data['commander'].get('docked') and '.'+data.get('lastStarport', {}).get('name', 'Unknown') or '', strftime('%Y-%m-%dT%H.%M.%S', localtime()))) if f: with open(f, 'wt') as h: h.write(json.dumps(data, ensure_ascii=False, indent=2, sort_keys=True, separators=(',', ': ')).encode('utf-8')) except companion.ServerError as e: self.status['text'] = str(e) except Exception as e: if __debug__: print_exc() self.status['text'] = unicode(e)
Example #3
Source File: root.py From PCWG with MIT License | 7 votes |
def ExportReport(self): preferences = Preferences.get() if self.analysis is None: Status.add("ERROR: Analysis not yet calculated", red=True) return try: fileName = tkFileDialog.asksaveasfilename(parent=self.root, defaultextension=".xls", initialfile="report.xls", title="Save Report", initialdir=preferences.analysis_last_opened_dir()) self.analysis.report(fileName) Status.add("Report written to %s" % fileName) except ExceptionHandler.ExceptionType as e: ExceptionHandler.add(e, "ERROR Exporting Report")
Example #4
Source File: base_dialog.py From PCWG with MIT License | 6 votes |
def validate_file_path(self): if len(self.filePath.get()) < 1: path = tkFileDialog.asksaveasfilename(parent=self.master,defaultextension=".xml", initialfile="%s.xml" % self.getInitialFileName(), title="Save New Config", initialdir=self.getInitialFolder()) self.filePath.set(path) if len(self.filePath.get()) < 1: tkMessageBox.showwarning( "File path not specified", "A file save path has not been specified, please try again or hit cancel to exit without saving.") return 0 if self.originalPath != None and self.filePath.get() != self.originalPath and os.path.isfile(self.filePath.get()): result = tkMessageBox.askokcancel( "File Overwrite Confirmation", "Specified file path already exists, do you wish to overwrite?") if not result: return 0 return 1
Example #5
Source File: chunkparser_app.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
def save_grammar(self, filename=None): if not filename: ftypes = [('Chunk Gramamr', '.chunk'), ('All files', '*')] filename = tkFileDialog.asksaveasfilename(filetypes=ftypes, defaultextension='.chunk') if not filename: return if (self._history and self.normalized_grammar == self.normalize_grammar(self._history[-1][0])): precision, recall, fscore = ['%.2f%%' % (100*v) for v in self._history[-1][1:]] elif self.chunker is None: precision = recall = fscore = 'Grammar not well formed' else: precision = recall = fscore = 'Not finished evaluation yet' out = open(filename, 'w') out.write(self.SAVE_GRAMMAR_TEMPLATE % dict( date=time.ctime(), devset=self.devset_name, precision=precision, recall=recall, fscore=fscore, grammar=self.grammar.strip())) out.close()
Example #6
Source File: chartparser_app.py From luscan-devel with GNU General Public License v2.0 | 6 votes |
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)
Example #7
Source File: __init__.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
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)
Example #8
Source File: sqlite_bro.py From sqlite_bro with MIT License | 6 votes |
def new_db(self, filename=''): """create a new database""" if filename == '': filename = filedialog.asksaveasfilename( initialdir=self.initialdir, defaultextension='.db', title="Define a new database name and location", filetypes=[("default", "*.db"), ("other", "*.db*"), ("all", "*.*")]) if filename != '': self.database_file = filename if os.path.isfile(filename): self.set_initialdir(filename) if messagebox.askyesno( message='Confirm Destruction of previous Datas ?', icon='question', title='Destroying'): os.remove(filename) self.conn = Baresql(self.database_file) self.actualize_db()
Example #9
Source File: sqlite_bro.py From sqlite_bro with MIT License | 6 votes |
def sav_script(self): """save a script in a file""" active_tab_id = self.n.notebook.select() if active_tab_id != '': # get current selection (or all) fw = self.n.fw_labels[active_tab_id] script = fw.get(1.0, END)[:-1] filename = filedialog.asksaveasfilename( initialdir=self.initialdir, defaultextension='.db', title="save script in a sql file", filetypes=[("default", "*.sql"), ("other", "*.txt"), ("all", "*.*")]) if filename != "": self.set_initialdir(filename) with io.open(filename, 'w', encoding='utf-8') as f: if "你好 мир Artisou à croute" not in script: f.write("/*utf-8 tag : 你好 мир Artisou à croute*/\n") f.write(script)
Example #10
Source File: sqlite_bro.py From sqlite_bro with MIT License | 6 votes |
def exsav_script(self): """write script commands + top results to a log file""" # idea from http://blog.mp933.fr/post/2014/05/15/Script-vs.-copy/paste active_tab_id = self.n.notebook.select() if active_tab_id != '': # get current selection (or all) fw = self.n.fw_labels[active_tab_id] script = fw.get(1.0, END)[:-1] filename = filedialog.asksaveasfilename( initialdir=self.initialdir, defaultextension='.db', title="execute Script + output in a log file", filetypes=[("default", "*.txt"), ("other", "*.log"), ("all", "*.*")]) if filename == "": return self.set_initialdir(filename) with io.open(filename, 'w', encoding='utf-8') as f: if "你好 мир Artisou à croute" not in script: f.write("/*utf-8 tag : 你好 мир Artisou à croute*/\n") self.create_and_add_results(script, active_tab_id, limit=99, log=f) fw.focus_set() # workaround bug http://bugs.python.org/issue17511
Example #11
Source File: sqlite_bro.py From sqlite_bro with MIT License | 6 votes |
def export_csv_dialog(self, query="--", text="undefined.csv", actions=[]): """export csv dialog""" # proposed encoding (we favorize utf-8 or utf-8-sig) encodings = ["utf-8", locale.getdefaultlocale()[1], "utf-16", "utf-8-sig"] if os.name == 'nt': encodings = ["utf-8-sig", locale.getdefaultlocale()[1], "utf-16", "utf-8"] # proposed csv separator default_sep = [",", "|", ";"] csv_file = filedialog.asksaveasfilename( initialdir=self.initialdir, defaultextension='.db', title=text, filetypes=[("default", "*.csv"), ("other", "*.txt"), ("all", "*.*")]) if csv_file != "": # Idea from (http://www.python-course.eu/tkinter_entry_widgets.php) fields = ['', ['csv Name', csv_file, 'r', 100], '', ['column separator', default_sep], ['Header line', True], ['Encoding', encodings], '', ["Data to export (MUST be 1 Request)", (query), 'w', 100, 10]] create_dialog(("Export to %s" % csv_file), fields, ("Export", export_csv_ok), actions)
Example #12
Source File: tkgui.py From ATX with Apache License 2.0 | 6 votes |
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)
Example #13
Source File: configurator.py From Enrich2 with BSD 3-Clause "New" or "Revised" License | 6 votes |
def menu_saveas(self): if self.root_element is None: tkMessageBox.showwarning(None, "Cannot save empty configuration.") else: fname = tkFileDialog.asksaveasfilename() if len(fname) > 0: # file was selected try: with open(fname, "w") as handle: write_json(self.root_element.serialize(), handle) except IOError: tkMessageBox.showerror(None, "Failed to save config file.") else: self.cfg_file_name.set(fname) tkMessageBox.showinfo( None, "Save successful:\n{}".format(self.cfg_file_name.get()) )
Example #14
Source File: root.py From PCWG with MIT License | 6 votes |
def ExportPDM(self): preferences = Preferences.get() if self.analysis is None: Status.add("ERROR: Analysis not yet calculated", red=True) return try: fileName = tkFileDialog.asksaveasfilename(parent=self.root, defaultextension=".xml", initialfile="power_deviation_matrix.xml", title="Save Report", initialdir=preferences.analysis_last_opened_dir()) self.analysis.report_pdm(fileName) Status.add("Power Deviation Matrix written to %s" % fileName) except ExceptionHandler.ExceptionType as e: ExceptionHandler.add(e, "ERROR Exporting Report")
Example #15
Source File: Tkeditor.py From Tkinter-Projects with MIT License | 6 votes |
def save_as(): try: # Getting a filename to save the file. f = tkFileDialog.asksaveasfilename(initialfile='Untitled.txt',defaultextension=".txt",filetypes=[("All Files","*.*"),("Text Documents","*.txt")]) fh = open(f, 'w') global filename filename = f textoutput = textPad.get(1.0, END) fh.write(textoutput) fh.close() root.title(os.path.basename(f) + " - Tkeditor") # Setting the title of the root widget. except: pass ###################################################################### #defining icons for compund menu demonstration
Example #16
Source File: MiniNAM.py From MiniNAM with GNU General Public License v2.0 | 6 votes |
def savePrefs( self ): "Save preferences and filters." myFormats = [ ('Config File','*.config'), ('All Files','*'), ] savingDictionary = {} fileName = tkFileDialog.asksaveasfilename(filetypes=myFormats ,title="Save preferences and filters as...") if len(fileName ) > 0: # Save Application preferences savingDictionary['preferences'] = self.appPrefs # Save Application filters savingDictionary['filters'] = self.appFilters try: f = open(fileName, 'wb') f.write(json.dumps(savingDictionary, sort_keys=True, indent=4, separators=(',', ': '))) # pylint: disable=broad-except except Exception as er: print er # pylint: enable=broad-except finally: f.close()
Example #17
Source File: MiniNAM.py From MiniNAM with GNU General Public License v2.0 | 6 votes |
def savePrefs( self ): "Save preferences and filters." myFormats = [ ('Config File','*.config'), ('All Files','*'), ] savingDictionary = {} fileName = tkFileDialog.asksaveasfilename(filetypes=myFormats ,title="Save preferences and filters as...") if len(fileName ) > 0: # Save Application preferences savingDictionary['preferences'] = self.appPrefs # Save Application filters savingDictionary['filters'] = self.appFilters try: f = open(fileName, 'wb') f.write(json.dumps(savingDictionary, sort_keys=True, indent=4, separators=(',', ': '))) # pylint: disable=broad-except except Exception as er: print er # pylint: enable=broad-except finally: f.close()
Example #18
Source File: MiniNAM.py From MiniNAM with GNU General Public License v2.0 | 6 votes |
def savePrefs( self ): "Save preferences and filters." myFormats = [ ('Config File','*.config'), ('All Files','*'), ] savingDictionary = {} fileName = tkFileDialog.asksaveasfilename(filetypes=myFormats ,title="Save preferences and filters as...") if len(fileName ) > 0: # Save Application preferences savingDictionary['preferences'] = self.appPrefs # Save Application filters savingDictionary['filters'] = self.appFilters try: f = open(fileName, 'wb') f.write(json.dumps(savingDictionary, sort_keys=True, indent=4, separators=(',', ': '))) # pylint: disable=broad-except except Exception as er: print er # pylint: enable=broad-except finally: f.close()
Example #19
Source File: MiniNAM.py From MiniNAM with GNU General Public License v2.0 | 6 votes |
def savePrefs( self ): "Save preferences and filters." myFormats = [ ('Config File','*.config'), ('All Files','*'), ] savingDictionary = {} fileName = tkFileDialog.asksaveasfilename(filetypes=myFormats ,title="Save preferences and filters as...") if len(fileName ) > 0: # Save Application preferences savingDictionary['preferences'] = self.appPrefs # Save Application filters savingDictionary['filters'] = self.appFilters try: f = open(fileName, 'wb') f.write(json.dumps(savingDictionary, sort_keys=True, indent=4, separators=(',', ': '))) # pylint: disable=broad-except except Exception as er: print er # pylint: enable=broad-except finally: f.close()
Example #20
Source File: chart.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
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)
Example #21
Source File: DeviceManager.py From python-dvr with MIT License | 6 votes |
def export(self): filename = asksaveasfilename( filetypes=( (_("JSON files"), "*.json"), (_("HTML files"), "*.html;*.htm"), (_("Text files"), "*.csv;*.txt"), (_("All files"), "*.*"), ) ) if filename == "": return ProcessCMD(["log", filename]) ProcessCMD(["loglevel", str(100)]) if ".json" in filename: ProcessCMD(["json"]) elif ".csv" in filename: ProcessCMD(["csv"]) elif ".htm" in filename: ProcessCMD(["html"]) else: ProcessCMD(["table"]) ProcessCMD(["loglevel", str(10)])
Example #22
Source File: easygui.py From mantaray with GNU General Public License v3.0 | 5 votes |
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 # #-------------------------------------------------------------------
Example #23
Source File: fileintegrity.py From darkc0de-old-stuff with GNU General Public License v3.0 | 5 votes |
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")
Example #24
Source File: gimodule.py From geoist with MIT License | 5 votes |
def showfilebrowser(self): import tkFileDialog filetypes = [('Output File','*.out'), ('Any File','*.*')] file = tkFileDialog.asksaveasfilename(title='Save File', filetypes=filetypes) try: #Only do something if a file has been selected. if file: self.textentry.delete(0,255) self.textentry.insert(0, file) except: #If no file has been selected do nothing. pass
Example #25
Source File: plot.py From tadtool with MIT License | 5 votes |
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))
Example #26
Source File: plot.py From tadtool with MIT License | 5 votes |
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]))
Example #27
Source File: plot.py From tadtool with MIT License | 5 votes |
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")
Example #28
Source File: base_dialog.py From PCWG with MIT License | 5 votes |
def __call__(self): fileName = tkFileDialog.asksaveasfilename(parent=self.master,defaultextension=".xml") if len(fileName) > 0: self.variable.set(fileName)
Example #29
Source File: IDMapper.py From DICAT with GNU General Public License v3.0 | 5 votes |
def createfilename(self): self.filename = tkFileDialog.asksaveasfilename( defaultextension=[("*.xml")], filetypes=[("XML files", "*.xml")] ) self.entryVariable.set(self.filename) if self.filename: open(self.filename, 'w') # Load the data self.LoadXML(self.filename) return self.filename
Example #30
Source File: fuctup_comments.py From darkc0de-old-stuff with GNU General Public License v3.0 | 5 votes |
def save(): output1 = textbox.get(1.0, END) str(output1) filename = tkFileDialog.asksaveasfilename() fileit = open(filename, "w") fileit.write(output1)