我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用tkinter.filedialog.asksaveasfilename()。
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 on_save_json(self, *args): """Triggered when save-button is clicked. Displays a save dialog, fetches GUI data into merge, and saves as JSON into the selected file.""" self.notify_task('Saving..', 0) _filename = filedialog.asksaveasfilename(initialfile= self.filename, defaultextension=".json", filetypes=[('JSON files', '.json'), ('all files', '.*')], title="Choose location") if _filename: self._gui_to_merge() self.notify_task('Saving(Generating JS)..', 0) _json = self.merge.as_json() self.notify_task('Saving(Writing file)..', 50) with open (_filename, "w") as _f: json.dump(_json, fp=_f, sort_keys=True, indent=4) self.notify_task('Saving..done.', 100) else: self.notify_task('Saving cancelled.', 0)
def print_to_file(self, filename=None): """ Print the contents of this ``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: str :rtype: None """ if filename is None: from tkinter.filedialog 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'): with open(filename, 'wb') as outfile: pickle.dump((self._chart, self._tokens), outfile) else: with open(filename, 'w') as outfile: 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: outfile.write('%s\n' % prod) for prod in rest: outfile.write('%s\n' % prod) except Exception as e: tkinter.messagebox.showerror('Error Saving Grammar', 'Unable to open file: %r' % filename)
def on_save_json(self, *args): """Triggered when save-button is clicked. Displays a save dialog, fetches GUI data into merge, and saves as JSON into the selected file.""" self.notify_task('Saving..', 0) _filename = filedialog.asksaveasfilename(initialdir=os.path.dirname(self.setup_filename.get()), initialfile=os.path.basename(self.setup_filename.get()) , defaultextension=".json", filetypes=[('JSON files', '.json'), ('all files', '.*')], title="Choose location") if _filename: self.gui_to_setup() self.notify_task('Saving(Generating JS)..', 0) _dict = self.setup.as_dict() self.notify_task('Saving(Writing file)..', 50) with open (_filename, "w") as _f: json.dump(_dict, fp=_f, sort_keys=True, indent=4) self.notify_task('Saving..done.', 100) else: self.notify_task('Saving cancelled.', 0)
def select_file(self, _default_extension, _file_types): """Brings up a selector dialog, prompting the user to select a file, the relative path if the file is then saved to the filename property. Also, the base path is set. """ if self.is_destination is True: _filename = filedialog.asksaveasfilename(initialdir=os.path.dirname(self.filename.get()), defaultextension=_default_extension, filetypes=_file_types, title="Choose destination file") else: _filename = filedialog.askopenfilename(initialdir=os.path.dirname(self.filename.get()), defaultextension=_default_extension, filetypes=_file_types, title="Choose source file") if _filename: self.base_path = os.path.dirname(_filename) self.filename.set(os.path.relpath(_filename, self.base_path))
def main_dumpROM(): global ROMbuffer global USBbuffer ROMfileName=asksaveasfilename(defaultextension=".GB",filetypes=(("GB ROM File","*.GB"),("GBC ROM File","*.GBC"),("GBA ROM File","*.GBA"),("All Files","*.*"))) if ROMfileName: ROMfile=open(ROMfileName,'wb') for bankNumber in range(0,(int(ROMsize/BankSize))): print ('Dumping ROM:',int(bankNumber*BankSize),' of ',ROMsize) if bankNumber == 0: ROMaddress=0 #get bank 0 from address 0, not setbank(0) and get from high bank... else: ROMaddress=BankSize main_ROMBankSwitch(bankNumber) #switch to new bank. for packetNumber in range(0,(int(BankSize/64))): AddHi=ROMaddress>>8 AddLo=ROMaddress&0xFF dev.write(0x01,[0x10,0x00,0x00,AddHi,AddLo]) ROMbuffer= dev.read(0x81,64) ROMfile.write(ROMbuffer) ROMaddress += 64 ROMfile.close() print ('Done!')
def main_dumpMXROM(): global ROMbuffer global USBbuffer ROMfileName=asksaveasfilename(filetypes=(("GB ROM File","*.GB"),("GBC ROM File","*.GBC"),("GBA ROM File","*.GBA"),("All Files","*.*"))) if ROMfileName: ROMfile=open(ROMfileName,'wb') for bankNumber in range(0,(int(ROMsize/BankSize))): print ('Dumping ROM:',int(bankNumber*BankSize),' of ',ROMsize) if bankNumber == 0: ROMaddress=0 #get bank 0 from address 0, not setbank(0) and get from high bank... else: ROMaddress=BankSize main_MXROMBankSwitch(bankNumber) #switch to new bank. for packetNumber in range(0,(int(BankSize/64))): AddHi=ROMaddress>>8 AddLo=ROMaddress&0xFF dev.write(0x01,[0x10,0x00,0x00,AddHi,AddLo]) ROMbuffer= dev.read(0x81,64) ROMfile.write(ROMbuffer) ROMaddress += 64 ROMfile.close() print ('Done!')
def main_GBA_Dump(): ROMfileName=asksaveasfilename(defaultextension=".GBA",filetypes=(("GBA ROM File","*.GBA"),("All Files","*.*"))) Hi2=0 if ROMfileName: ROMfile=open(ROMfileName,'wb') Address=0 for Address in range(0,int(ROMsize/2),32): Lo=Address&0xFF Me=(Address&0xFF00) >> 8 Hi=(Address&0xFF0000) >> 16 dev.write(0x01,[0x30,0x00,Hi,Me,Lo]) ROMbuffer= dev.read(0x81,64) ROMfile.write(ROMbuffer) if Hi2 != Hi: print(str(Address*2)+' Bytes of '+str(ROMsize)) Hi2=Hi ROMfile.close() print ('Done!')
def main_GBA_Dump64kFLASH(): #Test for SRAM First!!! RAMfileName=asksaveasfilename(defaultextension=".SAV",filetypes=(("GBA Save File","*.SAV"),("All Files","*.*"))) if RAMfileName: RAMfile=open(RAMfileName,'wb') Address=0 dev.write(0x01,[0x39,0x00,0x00,0x00,0x00,0x00]) RAMbuffer= dev.read(0x81,64) for Address in range(0,32768*2,64): Lo=Address&0xFF Me=(Address&0xFF00) >> 8 Hi=(Address&0xFF0000) >> 16 dev.write(0x01,[0x35,0x00,Hi,Me,Lo]) RAMbuffer= dev.read(0x81,64) RAMfile.write(RAMbuffer) RAMfile.close() print ('Done!')
def downfile(self): try: # ??????????????_??????????? filename = filedialog.asksaveasfilename() self.lfc_field_1_t.delete('0.0', 'end') self.lfc_field_1_t.insert('0.0', "??????......\n") filename = filename + '.' + \ requests.get("http://" + HOST + ":" + PORT + "/downfiletype").text self.lfc_field_1_t.insert('0.0', "?????????......") req = requests.get("http://" + HOST + ":" + PORT + "/downfile") if req.status_code == 200: with open(filename, 'wb') as savefile: savefile.write(req.content) messagebox.showinfo("??", "????") else: messagebox.showinfo("??", "????????") except: messagebox.showinfo("??", "????????") finally: self.lfc_field_1_t.delete('0.0', 'end')
def saveData(red=0, green=0, blue=0, clear=0, lux='0', colortemp='0'): # function used to save data taken by the sensor filename = filedialog.asksaveasfilename(filetypes=[('Text File', '*.txt')]) # asks for save file locatoin if os.path.isfile(filename): # checks if file exists os.remove(filename) # if it exists it is removed. file = open(filename, 'a+') # creates new file # writes to new file all data from sensor file.write(','.join(['Red: ' + str(red), 'Green: ' + str(green), 'Blue: ' + str(blue), 'Clear:' + str(clear), 'Luminosity: ' + lux, 'Color Temperature: ' + colortemp])) file.close() # closes file created # Enable interrupts and put the chip back to low power sleep/disabled.
def __init__(self, response=str, text="", title=None, accept=0, **options): if response is bool: self.dialog = [askyesno, askokcancel, askretrycancel][accept] else: self.dialog = {None:showinfo, str:askstring, int:askinteger, float:askfloat, 0:askopenfilename, 1:asksaveasfilename, 2:askdirectory}[response] self.options = options.copy() if "initialdir" in options: self.options["initialdir"] = abspath(options["initialdir"]) if type(response) is int: self.args = tuple() if title: self.options["title"] = title else: if title is None: title = "Info" if response is None else "Confirm" if response is bool else "Input" self.args = title, text
def onSave(self): filename = asksaveasfilename(defaultextension='.txt', filetypes=(('Text files', '*.txt'), ('Python files', '*.py *.pyw'), ('All files', '*.*'))) if filename: with open(filename, 'w') as stream: stream.write(self.gettext())
def browseForFile(TkStringVar): TkStringVar.set(tkFileDialog.asksaveasfilename()) # Tkinter doesn't let you send arguments to functions, so we must make wrapper functions:
def save_as(self): save_object = Save(self) filename = filedialog.asksaveasfilename(defaultextension=".sim", filetypes=(("Simulation file", "*.sim"), ("All files", "*.*"))) if filename: self.filename = filename self.name.set(os.path.split(filename)[-1]) save_object.save_as(filename)
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 select_output(self) -> None: path = asksaveasfilename(title='Please select the path of the image to create.', defaultextension='.png', filetypes=[('PNG File', '*.png'), ('JPEG File', '*.jpg')]) if not path: return None self.file_output = path self.speed_scale.state(['!disabled']) self.btn_start['state'] = 'normal'
def saveFile(self): self.settings['lastFile'] = filedialog.asksaveasfilename(filetypes=[('JSON file', '.json'), ('All files', '*')], initialfile=self.settings['lastFile']) id = os.path.basename(self.settings['lastFile']) id = id.split('.')[0] # Return if file name was not chosen (user closed the dialog) if (len(id) < 1): return with open(os.path.join(os.getcwd(), 'settings.json'), mode='w') as file: file.write(json.dumps(self.settings)) try: with open(os.path.join(os.getcwd(), 'data', (str(id).lower() + '.json')), mode='w') as file: file.write(json.dumps(self.output)) except: return if (not (id in self.accountlist)): self.accountlist[id] = dict() try: with open(os.path.join(os.getcwd(), 'data', (str(id).lower() + '.0.json')), mode='r') as file: self.accountlist[id]['start'] = json.loads(file.read())['timestamp'] except: with open(os.path.join(os.getcwd(), 'data', (str(id).lower() + '.0.json')), mode='w') as file: self.output['timestamp'] = datetime.datetime.now().strftime("%Y-%m-%d<br>%H:%M:%S") file.write(json.dumps(self.output)) self.accountlist[id]['start'] = self.output['timestamp'] self.accountlist[id]['id'] = id self.accountlist[id]['filename'] = self.settings['lastFile'] self.accountlist[id]['stop'] = self.output['timestamp'] try: self.accountlist[id]['odometer'] = self.data.current['truck']['odometer'] except: self.accountlist[id]['odometer'] = 0 self.accountlist[id]['distance'] = self.output['totalDistanceDriven'] self.accountlist[id]['totalFuel'] = self.output['fuelUsed'] self.accountlist[id]['averageFuel'] = self.output['averageFuelConsumption'] self.accountlist[id]['averageSpeed'] = self.output['averageSpeed'] self.accountlist[id]['rating'] = 'N/A' #TODO: Make rating system with open(os.path.join(os.getcwd(), 'data', ('accountlist.json')), mode='w') as file: file.write(json.dumps(self.accountlist))
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
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
def match(*, label="NluCell", topic=""): """Match subgraph and download. """ database = Database(password="train") if topic: cypher_info = "MATCH (n:{label}) WHERE n.topic='{topic}' RETURN n" else: cypher_info = "MATCH (n:{label}) RETURN n" filename = asksaveasfilename(filetypes=[('QA?excel??', '*.xls')]) keys = ['name', 'content', 'topic', 'tag', 'keywords', 'api', 'behavior', 'url', \ "hot", 'txt', 'img', 'chart', 'parameter'] # keys = database.graph.find_one(label).keys() items = database.graph.run(cypher_info.format(label=label, topic=topic)).data() sheets = [{"name": label, "keys": keys, "items": items}] write_excel(filename=filename, sheets=sheets)
def select_file(self): options = {'defaultextension':'apkg', 'parent':self, 'title':'Select the Anki deck location'} self.filename = filedialog.asksaveasfilename(**options) if self.filename != '': self.file_entry.delete(0, tkinter.END) self.file_entry.insert(0, self.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 file_new(self, event=None): file_name = filedialog.asksaveasfilename() if file_name: self.open_file = file_name self.main_text.delete(1.0, tk.END) self.title(" - ".join([self.WINDOW_TITLE, self.open_file]))
def file_save(self, event=None): if not self.open_file: new_file_name = filedialog.asksaveasfilename() if new_file_name: self.open_file = new_file_name if self.open_file: new_contents = self.main_text.get(1.0, tk.END) with open(self.open_file, "w") as open_file: open_file.write(new_contents)