def generate_java(canvas): jname=canvas.statusbar.getState(StatusBar.MODEL)[1][0] if not jname or jname=="Nonamed": jname=tkFileDialog.asksaveasfilename(filetypes=[("Java source code", "*.java")]) else: if StringUtil.endswith(jname, ".py"): jname=jname[:len(jname)-3]+".java" jname=os.path.split(jname)[1] jname=tkFileDialog.asksaveasfilename(initialfile=jname, filetypes=[("Java source code", "*.java")], initialdir=canvas.codeGenDir) if jname: if StringUtil.endswith(jname, ".java"): mname=jname[:len(jname)-5]+".des" else: mname=jname+".java" desc=generate_description(canvas, 0)["desc"] eventhandler=EventHandler(mname, modeltext=desc) g=JavaGenerator(eventhandler) code=g.generate_code() # Save .java file jf=open(jname, "w") jf.write(code) jf.close() # Print on success print "Java code saved to: " + jname
def setupProfiles(self): self.profileDialog=Toplevel(self.parent) self.fileBoxText=StringVar() msg=Message(self.profileDialog,text='This is your first time accessing profiles!\n\nProfiles allow you to save settings that work well for a particular journal or set of journals. \n\nTo begin, select the file in which to save your profile parameters:') msg.grid(row=0,column=0,sticky=W) fileBox=Entry(self.profileDialog,width=50,textvariable=self.fileBoxText) self.fileBoxText.set('./journal2ebook.txt') fileBox.grid(row=1,column=0,sticky=W) bBrowse=Button(self.profileDialog) bBrowse.configure(text='Browse') bBrowse.bind('<Button-1>',lambda event:self.fileBoxText.set(asksaveasfilename(parent=self.profileDialog,))) bBrowse.bind('<Return>',lambda event:self.fileBoxText.set(asksaveasfilename(parent=self.profileDialog,))) bBrowse.grid(row=1,column=1,sticky=W) bOK=Button(self.profileDialog) bOK.configure(text='OK') bOK.focus_force() bOK.bind('<Button-1>',self.profilesOK) bOK.bind('<Return>',self.profilesOK) bOK.grid(row=2,column=0,sticky=E) bCancel=Button(self.profileDialog) bCancel.configure(text='Cancel') bCancel.bind('<Button-1>',lambda event: self.profileDialog.destroy()) bCancel.bind('<Return>',lambda event: self.profileDialog.destroy()) bCancel.grid(row=2,column=1,sticky=W)
def FindFile(self): oldfile = self.value if self.action == "open": if self.filetypes: browsevalue=tkFileDialog.askopenfilename(initialfile=self.value, filetypes=self.filetypes) self.browsevalue=str(browsevalue) else: browsevalue=tkFileDialog.askopenfilename(initialfile=self.value) self.browsevalue=str(browsevalue) else: # elif self.action == "save": if self.filetypes: browsevalue=tkFileDialog.asksaveasfilename(initialfile=self.value, filetypes=self.filetypes) self.browsevalue=str(browsevalue) else: browsevalue=tkFileDialog.asksaveasfilename(initialfile=self.value) self.browsevalue=str(browsevalue) if len(self.browsevalue) == 0: self.browsevalue = oldfile if self.command: #self.command() # We pass browsevalue through, although the previous binding means that # the command must also be capable of receiving a Tkinter event. # See the interfaces/dalton.py __update_script method self.command( self.browsevalue ) self.entry.setvalue(self.browsevalue) self.editor.calc.set_parameter(self.parameter,self.browsevalue) else: self.entry.setvalue(self.browsevalue) self.editor.calc.set_parameter(self.parameter,self.browsevalue)
def convertLib(): fileName=askopenfilename(title = "Input Library",filetypes=[('Eagle V6 Library', '.lbr'), ('all files', '.*')], defaultextension='.lbr') modFileName=asksaveasfilename(title="Module Output Filename", filetypes=[('KiCad Module', '.mod'), ('all files', '.*')], defaultextension='.mod') symFileName=asksaveasfilename(title="Symbol Output Filename", filetypes=[('KiCad Symbol', '.lib'), ('all files', '.*')], defaultextension='.lib') logFile.write("*******************************************\n") logFile.write("Converting Lib: "+fileName+"\n") logFile.write("Module Output: "+modFileName+"\n") logFile.write("Symbol Output: "+symFileName+"\n") name=fileName.replace("/","\\") name=name.split("\\")[-1] name=name.split(".")[0] logFile.write("Lib name: "+name+"\n") try: node = getRootNode(fileName) node=node.find("drawing").find("library") lib=Library(node,name) modFile=open(modFileName,"a") symFile=open(symFileName,"a") lib.writeLibrary(modFile,symFile) except Exception as e: showerror("Error",str(e)+"\nSee Log.txt for more info") logFile.write("Conversion Failed\n\n") logFile.write(traceback.format_exc()) logFile.write("*******************************************\n\n\n") return logFile.write("Conversion Successfull\n") logFile.write("*******************************************\n\n\n") showinfo("Library Complete","The Modules and Symbols Have Finished Converting \n Check Console for Errors")
def doThings(ratio=gearRatio, overlap=gearOverlap, steps=computationSteps): inputGear = loadGearImage() offset = (ratio+1-overlap, 0) inputCoords, inputImageSize = getBlackPixels(inputGear, offset) outputImageSize = inputImageSize*ratio outputGear = np.zeros([outputImageSize, outputImageSize]) theta = 2*np.pi/steps phi = 2*np.pi/(steps*ratio) # Rotation math for step in range(steps): coords = rotatePts(inputCoords, offset, theta*step) addPoints = [] for coord in coords: if dist(*coord)<ratio: addPoints += [coord] # Rotate the points that contribute to the output gear's profile for extraRotation in range(ratio): rotateBy = phi*step + 2*np.pi*extraRotation/ratio addPointsRot = rotatePts(addPoints, (0,0), rotateBy) # Convert those points into pixels, draw on output gear outputGear = outputGearImage(outputGear, addPointsRot, outputImageSize, ratio) print('Progress: {}/{}'.format(step, steps)) # Debug # Clean up image outputGear = outputCleanup(outputGear) # Should also make little marks for centroids and distances # Animate? # Save image outFilename = tkFileDialog.asksaveasfilename(defaultextension='.png', initialfile='gear_output') writeOutputGear(outputGear, outFilename) # save the crossbar image too crossbar = drawCrossbar(inputImageSize*(ratio+1-overlap)/2) outFilename = tkFileDialog.asksaveasfilename(defaultextension='.png', initialfile='crossbar') writeOutputGear(crossbar, outFilename)
def _check_browse(self, index): if index == 0: return tkFileDialog.askopenfilename(defaultextension = FILES_JPT[0][1], filetypes = FILES_JPT) if index == 1: return tkFileDialog.asksaveasfilename(defaultextension = FILES_JPEG[0][1], filetypes = FILES_JPEG) if index == 2: return tkFileDialog.asksaveasfilename(defaultextension = FILES_PNG[0][1], filetypes = FILES_PNG) return FrameJpt._check_browse(index)
def export_plot_data(self): if self.export_type == 'hist1d' or self.export_type == 'scatter': data_path = tkFileDialog.asksaveasfilename(defaultextension='.csv') np.savetxt(data_path,np.c_[self.xdata,self.ydata],delimiter=',') elif self.export_type == 'hist2d': data_path = tkFileDialog.asksaveasfilename(defaultextension='.csv') np.savetxt(data_path,np.c_[self.xdata,self.ydata,self.zdata],delimiter=',') else: self.status_string.set("Unable to export plot")
def exportMidiFile(self): #takes the current music on piano roll and exports it as a midi file self.createTimingTrack() timingTrack=self.noteTimingList if self.fileName!=None: fileName = tkFileDialog.asksaveasfilename(initialfile= [self.fileName]) else:fileName = tkFileDialog.asksaveasfilename(initialfile=['New.mid']) if fileName!='': #if there is a file name CreateMidi(fileName,timingTrack,self.ticksPerBeat)
def saveDonorsFile(self): if (self.filename): self.filename = tkFileDialog.asksaveasfilename( defaultextension="xmas", parent=self, initialfile=self.filename) else: self.filename = tkFileDialog.asksaveasfilename( defaultextension="xmas", parent=self, initialdir=".") if (self.filename): print self.donors.str() self.outputFile = open(self.filename, 'w') self.outputFile.write(self.donors.str()) self.outputFile.close()
def ask_savefile(initialfolder='.',title='Save As',types=None): """Open a native file "save as" dialog that asks the user to choose a filename. The path is returned as a string. Specify types in the format ['.bmp|Windows Bitmap','.gif|Gif image'] and so on. """ import tkFileDialog if types!=None: aTypes = [(type.split('|')[1],type.split('|')[0]) for type in types] defaultExtension = aTypes[0][1] strFiles = tkFileDialog.asksaveasfilename(initialdir=initialfolder,title=title,defaultextension=defaultExtension,filetypes=aTypes) else: strFiles = tkFileDialog.asksaveasfilename(initialdir=initialfolder,title=title) return strFiles
def _ask_path_to_file(self): """ Ask a path to the destination file. If a dir has been already specified, open the choice window showing this dir. """ if not self.homeDir: fullPath = asksaveasfilename(**_DialogueLabels.save_output_file_choice) else: fullPath = asksaveasfilename(initialdir = self.homeDir, **_DialogueLabels.save_output_file_choice) if fullPath: dir, filename = os.path.split(fullPath) if dir: self.homeDir = dir return fullPath
def getFiletoSave(initialDir="",title=""): root = tk.Tk() if(title == ""): title = "Please select a file name to be saved" root.withdraw() if(initialDir != ""): file_path = tkFileDialog.asksaveasfilename(initialdir=initialDir,title=title) else: file_path = tkFileDialog.asksaveasfilename() root.destroy() return file_path
def saveImg(self): if self.operation.get() == 1 and self.encryptDone: savePath = tkFileDialog.asksaveasfilename(parent = self.frame, initialdir = '/home/st/Pictures', title = 'Save Encryted Data Image', filetypes = [('BMP', '.bmp'), ('PNG', '.png')]) if savePath != "": self.dataImage.save(savePath) tkMessageBox.showinfo('Infos', 'Encrypted Image Save Success!\npath: %s' % savePath) elif self.operation.get() == 2 and self.decryptData is not None: savePath = tkFileDialog.asksaveasfilename(parent = self.frame, initialdir = '/home/st/', title = 'Save Decryted Data File') if savePath != "": saveFile = open(savePath, 'w') saveFile.writelines(self.decryptData) saveFile.close() tkMessageBox.showinfo('Infos', 'Dncrypted Data File Save Success!\npath: %s' % savePath)
def askSaveAsFilename(filetypes=None, initialfile=None): " returns empty string if unsuccessful" ft = [] if filetypes != None: ft.append( (filetypes,filetypes )) # "*.dat" --> ("*.dat", "*.dat") if initialfile == None: f = asksaveasfilename(filetypes=ft) else: f = asksaveasfilename(filetypes=ft, initialfile=initialfile) if type(f) == type(()): return "" else: #f = string.replace(f,"/tmp_mnt","") return f
def save_network(self,type="square"): network=self.distancematrix netfilename=tkFileDialog.asksaveasfilename(title="Select file for the distance matrix") if len(netfilename)==0: return netfile=open(netfilename,"w") nodes=netio.writeNet_mat(network,netfile,type=type) nodefilename=tkFileDialog.asksaveasfilename(title="Select file for node names") if len(nodefilename)>0: nodefile=open(nodefilename,"w") for node in nodes: nodefile.write(str(node)+"\n") tkMessageBox.showinfo(message='Save succesful.') else: tkMessageBox.showinfo(message='Save succesful.\nNode names not saved.')
def save_iso2flux_model(label_model,name="project",write_sbml=True,ask_sbml_name=False,gui=False): project_name=name if gui: tk=Tkinter.Tk() tk.withdraw() project_name = tkFileDialog.asksaveasfilename(parent=tk,title="Save project as...",filetypes=[("iso2flux",".iso2flux")]) if ".iso2flux" not in project_name: project_name+=".iso2flux" if write_sbml and ask_sbml_name: sbml_name=tkFileDialog.asksaveasfilename(parent=tk,title="Save reference SBML model as...",filetypes=[("sbml",".sbml"),("xml",".xml")]) if ".sbml" not in sbml_name: sbml_name+=".sbml" tk.destroy() project_dict={} #project_dict["condition_size_yy_dict"]=label_model.condition_size_yy_dict #project_dict["condition_size_yy0_dict"]=label_model.condition_size_yy0_dict project_dict["eqn_dir"]=label_model.eqn_dir project_dict["reaction_n_dict"]=label_model.reaction_n_dict project_dict["merged_reactions_reactions_dict"]=label_model.merged_reactions_reactions_dict project_dict["force_balance"]=label_model.force_balance project_dict["ratio_dict"]=label_model.ratio_dict project_dict["parameter_dict"]=label_model.parameter_dict project_dict["turnover_flux_dict"]=label_model.turnover_flux_dict project_dict["size_variable_dict"]=label_model.size_variable_dict project_dict["emu_dict"]=label_model.emu_dict project_dict["rsm_list"]=label_model.rsm_list project_dict["emu_size_dict"]=label_model.emu_size_dict project_dict["initial_label"]=label_model.initial_label project_dict["experimental_dict"]=label_model.experimental_dict project_dict["input_m0_list"]=label_model.input_m0_list project_dict["input_n_dict"]=label_model.input_n_dict project_dict["data_name_emu_dict"]=label_model.data_name_emu_dict project_dict["lp_tolerance_feasibility"]=label_model.lp_tolerance_feasibility project_dict["parameter_precision"]=label_model.parameter_precision project_dict["metabolite_id_isotopomer_id_dict"]=label_model.metabolite_id_isotopomer_id_dict project_dict["isotopomer_id_metabolite_id_dict"]=label_model.isotopomer_id_metabolite_id_dict project_dict["reactions_propagating_label"]=label_model.reactions_propagating_label project_dict["label_groups_reactions_dict"]=label_model.label_groups_reactions_dict #project_dict["label_groups_reactions_dict"]=label_model.label_groups_reactions_dict project_dict["p_dict"]=label_model.p_dict if write_sbml: if ask_sbml_name==False or gui==False: sbml_name=project_name[:-9]+"_iso2flux.sbml" cobra.io.write_sbml_model(label_model.metabolic_model, sbml_name) with open(project_name, 'w') as fp: json.dump(project_dict, fp) label_model.project_name=project_name.split("/")[-1] return project_name
def handleExportEntityTree(self): try: selectedEntId = self.selectedEntity.entId except AttributeError: self.editor.showWarning('Please select a valid entity first.', 'error') return import tkFileDialog filename = tkFileDialog.asksaveasfilename(parent=self.editor.parent, defaultextension='.egroup', filetypes=[('Entity Group', '.egroup'), ('All Files', '*')]) if len(filename) == 0: return eTree = {} eGroup = {} def addEntity(entId, treeEntry): treeEntry[entId] = {} eGroup[entId] = self.levelSpec.getEntitySpecCopy(entId) entity = self.getEntity(entId) for child in entity.getChildren(): addEntity(child.entId, treeEntry[entId]) addEntity(selectedEntId, eTree) for entId, spec in eGroup.items(): eGroup[entId] = self.specPrePickle(spec) try: import pickle f = open(filename, 'w') pickle.dump(eTree, f) pickle.dump(eGroup, f) except: self.editor.showWarning("Error exporting entity group to '%s'." % filename, 'error') return
def report(self): ''' generate the report, run by clicking Button ''' if self.year.get() is '': self.output_text("! - Please Select a Year") return if self.month.get() is '': self.output_text("! - Please select a Month") return year = self.year.get() inputf = 'jim_data' + year + '.xlsx' month = self.month.get() outputf_def = month + year + '_report.xlsx' outputf = tkFileDialog.asksaveasfilename(parent=self, defaultextension='.xlsx', initialfile=outputf_def) if outputf is '': return #file not selected #output report month_report(inputf,month,year,outputf,self.customers,self.payments) self.output_text("* - " + self.month.get() + ' ' + self.year.get() + ' report saved to: ' + outputf + '\n') # print stat(outputf) if sys.platform == 'darwin': system('open ' + outputf + ' &') else: system(outputf) # open the file
def _save(self, *argv): if not self._preview(): return self.consoleNor("过程控制:图片正在处理中...") filepath = tkFileDialog.asksaveasfilename() filename = os.path.basename(filepath) dotNum = filename.count(".") if dotNum == 0: if filename == "" : return postfix = ".jpg" elif dotNum >= 2 or not (filename.split(".")[1] in IMAGE_TYPES): self.consoleErr("格式错误:文件名格式错误!") return else: postfix = "" if os.path.exists(self.filename) and fileCheck.isImage(self.filename): try: if self.algNum == 0: im = tool_cv2.resize_linear(self.filename, self.wScale, self.hScale) else: im = tool_cv2.resize_cubic(self.filename, self.wScale, self.hScale) self.consoleNor("过程控制:图片处理完毕,开始保存...") cv2.imwrite(filepath+postfix, im) self.consoleNor("过程控制:图片保存完毕...") except: self.consoleErr("过程控制:图片保存过程出现问题...") else: self.consoleErr("类型错误:打开的不是图片或者是文件不存在!")
def save_text(self): fname = tkFileDialog.asksaveasfilename() f = open(fname, "wb") for v in self.shot_dict.values(): line = "%s\n" % v f.write(line) pass
def save_file_dialog(initial_file='dipy.png', default_ext='.png', file_types=(("PNG file", "*.png"), ("All Files", "*.*"))): """ Simple Tk file dialog for saving a file Parameters ---------- initial_file : str For example ``dipy.png``. default_ext : str Default extension to appear in the save dialog. file_types : tuples of tuples Accepted file types. Returns ------- filepath : str Complete filename of saved file """ root = tkinter.Tk() root.withdraw() file_path = filedialog.asksaveasfilename(initialfile=initial_file, defaultextension=default_ext, filetypes=file_types) return file_path
def onSave(self): file_opt = options = {} options['filetypes'] = [('Image Files', '*.tif *.jpg *.png')] options['initialfile'] = 'myImage.jpg' options['parent'] = self.parent fname = tkFileDialog.asksaveasfilename(**file_opt) Image.fromarray(np.uint8(self.Ilast)).save(fname)
def saveFilename(self, ext='.txt'): filename=tkFileDialog.asksaveasfilename(defaultextension=ext, initialdir=os.getcwd(), filetypes=[("txt files","*.txt"), ("All files","*.*")], parent=self.main) return filename
def save_file(self): name = tkFileDialog.asksaveasfilename() if not name: return file = open(name, 'w') file_contents = self.text.get(0.0, END + "-1c") file.write(file_contents)
def ExportSecretaris(): # Obrim el fitxer de text # Així es com estava abans quan el ficava a /exportacions ----> f=open("exportacions/secretaris-ajuntaments.txt","w") fitxer = tkFileDialog.asksaveasfilename( defaultextension="*.txt|*.*", filetypes=[("Fitxer TXT", "*.txt"), ("Tots els fitxers", "*.*")] ) f = open(fitxer, "w") # Generamos el select para obtener los datos de la ficha db = MySQLdb.connect(host=SERVIDOR, user=USUARI, port=4406, passwd=CONTRASENYA, db=BASE_DE_DADES) cursor = db.cursor() sql = "SELECT MUNICIPIO, SECRETARIO FROM ayuntamientos ORDER BY MUNICIPIO" cursor.execute(sql) resultado = cursor.fetchall() for i in resultado: f.write(str(i[0]) + " - " + str(i[1]) + "\n") # tanquem el fitxer f.close() if len(fitxer) > 0: tkMessageBox.showinfo("TXT Generat", "S'ha generat la fitxa amb els secretaris a " + fitxer) else: return
def __saveToExcel(self): if len(self.__itemId) > 0: if self.__currentLoadType == "puts": data = self.__google_api.getPuts() else: data = self.__google_api.getCalls() finalData = [] finalData.append(list(self.__cols)) pickCol = pickColumns(data) for ind, fData in enumerate(pickCol): finalData.append(fData) dialogOption = { "filetypes" : [("All Files", ".*"), ("Excel File", ".xls")], "parent" : self.__root, "initialfile" : EXCEL_INITIAL_FILENAME } fname = tkFileDialog.asksaveasfilename(**dialogOption) if fname: writeToExcel(finalData, fname)
def ExportTimeSeries(self): if self.analysis is None: Status.add("ERROR: Analysis not yet calculated", red=True) return try: preferences = Preferences.get() selections = ExportDataSetDialog(self.root) clean, full, calibration = selections.get_selections() file_name = tkFileDialog.asksaveasfilename(parent=self.root, defaultextension=".csv", initialfile="timeseries.csv", title="Save Time Series", initialdir=preferences.analysis_last_opened_dir()) full_df_output_dir = "TimeSeriesData" self.analysis.export_time_series(file_name, clean, full, calibration, full_df_output_dir=full_df_output_dir) if clean: Status.add("Time series written to %s" % file_name) if any((full, calibration)): Status.add("Extra time series have been written to %s" % os.path.join(os.path.dirname(file_name), full_df_output_dir)) except ExceptionHandler.ExceptionType as e: ExceptionHandler.add(e, "ERROR Exporting Time Series")
def showSaveWindow(self): print "showSaveWindow to be completed after checkboxes" filename = tkFileDialog.asksaveasfilename(parent=self.root, filetypes=[('jdl files', '.jdl'), ('all files', '.*')], initialfile='*.jdl') raise NotImplementedError
def save(self): if self.data is None: return ax = self.fig.gca() start,end = ax.get_xlim() d = Dialog(self.root, "Save data", [ ("Start [{}]:".format(self.data.timeunit), start), ("End [{}]:".format(self.data.timeunit), end), ("Channel:", 0), ("WAV Rate [1/{}]:".format(self.data.timeunit), int(1/self.data.timescale)) ]) if d.result is None: return fname = tkFileDialog.asksaveasfilename(parent=self.root, filetypes=[('Envelope', '.txt .dat'), ('WAV','.wav'), ('BDAT','.bdat')]) if not fname: return start, end, channel, rate = d.result if fname[-4:] in [".txt", ".dat"]: from numpy import savetxt, transpose x,y = self.data.resample( (start,end), channel=channel, num=10000) savetxt(fname, transpose([x,y])) elif fname[-4:] == ".wav": r = int(start/self.data.timescale), int(end/self.data.timescale) self.data.save_wav(fname, range=r, channel=channel, rate=rate) elif fname[-5:] == ".bdat": r = int(start/self.data.timescale), int(end/self.data.timescale) self.data.save_bdat(fname, range=r, channel=channel)
def export_csv(): filename = asksaveasfilename(title="Save As", filetypes=[("csv file",".csv"),("All files",".*")]) if filename != '': output = 'IOC,Type\n' #need better way to iterate through highlights and remove brackets for t in tags: indicators = [] myhighlights = text.tag_ranges(t) mystart = 0 for h in myhighlights: if mystart == 0: mystart = h else: mystop = h if t == 'md5': #make all hashes uppercase if not text.get(mystart,mystop).upper() in indicators: indicators.append(text.get(mystart,mystop).upper()) else: if not text.get(mystart,mystop).replace('[.]','.').replace('[@]','@') in indicators: indicators.append(text.get(mystart,mystop).replace('[.]','.').replace('[@]','@')) mystart = 0 for i in indicators: if i.find(',') == -1: #no commas, print normally output += str(i) + ',' + t + '\n' else: #internal comma, surround in double quotes output += '"' + str(i) + '",' + t + '\n' if len(filename) - filename.find('.csv') != 4: filename += '.csv' #add .csv extension if missing with open(filename, 'w') as f: f.write(output)
def on_selectfile(self): global txtFName filetypes = (('NetCDF4 files', '*.nc4'), ) self.ncfname = asksaveasfilename(filetypes=filetypes) txtFName.set(self.ncfname)
def onSave(self): filename = asksaveasfilename() if filename: alltext = self.gettext() open(filename, 'w').write(alltext)
def saveFile(self): file_path = asksaveasfilename() self.check_mapping(file_path)
def save(self): path = tkFileDialog.asksaveasfilename(defaultextension=".png") if path is not '': self.im.save(path) if os.path.isfile('out.png'): os.remove('out.png')
def run(bk): # check if inifile exists if not os.path.isfile(ini_path): print("Borkify.ini not found. Using default settings.") write_ini(ini_path) # run plugin version check href = 'http://www.mobileread.com/forums/showpost.php?p=' '3138237&postcount=1' _latest_pattern = re.compile(r'Current Version:\s*"([^&]*)&') plugin_xml_path = os.path.abspath( os.path.join(bk._w.plugin_dir, 'Borkify', 'plugin.xml')) plugin_version = ET.parse(plugin_xml_path).find('.//version').text try: latest_version = None if PY2: response = urllib.urlopen(href) else: response = urllib.request.urlopen(href) m = _latest_pattern.search(response.read().decode('utf-8', 'ignore')) if m: latest_version = (m.group(1).strip()) if latest_version and latest_version != plugin_version: restype = 'info' filename = linenumber = None message = '*** An updated plugin version is available: v' + \ latest_version + ' ***' bk.add_result(restype, filename, linenumber, message) except: pass # read inifile read_ini(ini_path) # Extract book temp_dir = tempfile.mkdtemp() bk.copy_book_contents_to(temp_dir) # create mimetype file os.chdir(temp_dir) mimetype = open("mimetype", "w") mimetype.write("application/epub+zip") mimetype.close() # parse all xhtml/html files for mid, href in bk.text_iter(): print("..converting: ", href, " with manifest id: ", mid) data = borkify_xhtml(bk, mid, href) # write out modified file destdir = "" filename = unquote(href) if "/" in href: destdir, filename = unquote(filename).split("/") fpath = os.path.join(temp_dir, "OEBPS", destdir, filename) with open(fpath, "wb") as f: f.write(data.encode('utf-8')) # finally ready to build epub print("..creating 'borkified' ePUB") data = "application/epub+zip" fpath = os.path.join(temp_dir, "mimetype") with open(fpath, "wb") as f: f.write(data.encode('utf-8')) # ask the user where he/she wants to store the new epub doctitle = "dummy" fname = cleanup_file_name(doctitle) + "_borkified.epub" localRoot = tkinter.Tk() localRoot.withdraw() fpath = tkinter_filedialog.asksaveasfilename(parent=localRoot, title="Save ePUB as ...", initialfile=fname, initialdir=_USER_HOME, defaultextension=".epub") # localRoot.destroy() localRoot.quit() if not fpath: ignore_errors = sys.platform == 'win32' shutil.rmtree(temp_dir, ignore_errors) print("Borkify plugin cancelled by user") return 0 epub_zip_up_book_contents(temp_dir, fpath) ignore_errors = sys.platform == 'win32' shutil.rmtree(temp_dir, ignore_errors) print("Output Conversion Complete") # Setting the proper Return value is important. # 0 - means success # anything else means failure return 0
def get_output_filename(): output_filename=tkFileDialog.asksaveasfilename(title='Select output filename', filetypes=[('Output files', '*.txt'),("All files", "*.*")] ) if output_filename: Output_name.set(output_filename)
def get_fname(self): fname = tkFileDialog.asksaveasfilename() self.fname_label_text.set(fname)
def Execute(self): if self.Image == None: if self.Input == None: self.PrintError('Error: no Image.') self.Image = self.Input extensionFormats = { 'vti': 'vtkxml', 'vtkxml': 'vtkxml', 'vtk': 'vtk', 'mhd': 'meta', 'mha': 'meta', 'tif': 'tiff', 'png': 'png', 'dat': 'pointdata' } if self.OutputFileName == 'BROWSER': import tkFileDialog initialDir = '.' self.OutputFileName = tkFileDialog.asksaveasfilename( title="Output image", initialdir=initialDir) if not self.OutputFileName: self.PrintError('Error: no OutputFileName.') if self.OutputDirectoryName == 'BROWSER': import tkFileDialog initialDir = '.' self.OutputDirectoryName = tkFileDialog.askdirectory( title="Output directory", initialdir=initialDir) if not self.OutputDirectoryName: self.PrintError('Error: no OutputDirectoryName.') if self.GuessFormat and self.OutputFileName and not self.Format: import os.path extension = os.path.splitext(self.OutputFileName)[1] if extension: extension = extension[1:] if extension in extensionFormats.keys(): self.Format = extensionFormats[extension] if self.PixelRepresentation != '': cast = vtk.vtkImageCast() cast.SetInput(self.Image) if self.PixelRepresentation == 'double': cast.SetOutputScalarTypeToDouble() elif self.PixelRepresentation == 'float': cast.SetOutputScalarTypeToFloat() elif self.PixelRepresentation == 'short': cast.SetOutputScalarTypeToShort() else: self.PrintError('Error: unsupported pixel representation ' + self.PixelRepresentation + '.') cast.Update() self.Image = cast.GetOutput() if self.UseITKIO and self.Format not in [ 'vtkxml', 'tiff', 'png', 'dat' ]: self.WriteITKIO() else: if (self.Format == 'vtkxml'): self.WriteVTKXMLImageFile() elif (self.Format == 'vtk'): self.WriteVTKImageFile() elif (self.Format == 'meta'): self.WriteMetaImageFile() elif (self.Format == 'png'): self.WritePNGImageFile() elif (self.Format == 'tiff'): self.WriteTIFFImageFile() elif (self.Format == 'pointdata'): self.WritePointDataImageFile() else: self.PrintError('Error: unsupported format ' + self.Format + '.')
kmap = pygame.key.get_pressed() if event.key == pygame.K_q: os._exit(0) if event.key == pygame.K_ESCAPE: del points reinit_vars() stage = 0 if event.key == pygame.K_F4 and (kmap[pygame.K_LALT] or kmap[pygame.K_RALT]): os._exit(0) if event.key == pygame.K_RETURN: pygame.event.set_grab(0) pygame.mouse.set_visible(1) root = tk.Tk() root.withdraw() f = tkFileDialog.asksaveasfilename(defaultextension=".png") root.destroy() if f == (): pygame.mouse.set_visible(0) pygame.event.set_grab(1) continue if resize_on_save: tosave = pygame.Surface(window_size, pygame.SRCALPHA, 32) else: tosave = pygame.Surface((ww, hh), pygame.SRCALPHA, 32) tosave = tosave.convert_alpha() for pos1, pos2 in window(points, 2): if resize_on_save: p1 = scaler(pos1) p2 = scaler(pos2) else:
def save_filename(): """ 设置文件保存路径 """ savename = File.asksaveasfilename(title="择其去处",filetypes=[("xlsx file","*.xlsx"),("all files","*.*")],defaultextension='.xlsx') content02.set(savename)
def __save_image_dialog_cb(self, ev): filetypes = (("PNG files", "*.png"), ("All files", "*.*")) path = tkFileDialog.asksaveasfilename(filetypes=filetypes) if len(path) != 0: self.save_image(path) self.saving_filename = path
def generate(self): makelicense = ['univention_make_license'] path = tkFileDialog.asksaveasfilename(initialdir='~', initialfile=self.kname.get() + '-license', defaultextension='.ldif') #print path if path: if self.chkevar.get(): makelicense.append('-e') if self.chkivar.get(): makelicense.append('-i') makelicense.append('-f') makelicense.append(path) if not self.chkdvar.get(): makelicense.append('-d') makelicense.append( "%s/%s/%s" % (self.exmonth.get(), self.exday.get(), self.exyear.get())) if not self.chkovar.get(): if not self.chkmaxaccvar.get(): makelicense.append('-a') makelicense.append('%d' % self.kmaxacc.get()) else: makelicense.append('-a') makelicense.append('unlimited') if not self.chkmaxgaccvar.get(): makelicense.append('-g') makelicense.append('%d' % self.kmaxgacc.get()) else: makelicense.append('-g') makelicense.append('unlimited') if not self.chkmaxclivar.get(): makelicense.append('-c') makelicense.append('%d' % self.kmaxcli.get()) else: makelicense.append('-c') makelicense.append('unlimited') if not self.chkmaxdeskvar.get(): makelicense.append('-u') makelicense.append('%d' % self.kmaxdesk.get()) else: makelicense.append('-u') makelicense.append('unlimited') else: makelicense.append('-o') makelicense.append(self.kname.get()) makelicense.append(self.kdn.get()) os.chdir('/home/groups/99_license/') p = subprocess.Popen(makelicense, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) stdout, stderr = p.communicate() if p.returncode == 0: showinfo( 'Lizenz Erstellt!', 'Die Lizenz für %s wurde erfolgreich erstellt!' % self.kname.get()) elif p.returncode == 257: showerror( 'Fehler', 'Errorcode: "%s"\nEvtl. sind Sie nicht in dem Sudoers File!' % p.returncode) elif p.returncode == 8704: showerror( 'Fehler', 'Errorcode: "%s"\nmake_license.sh meldet: "invalid DN"!' % p.returncode) else: print >> sys.stderr, '%r\n%s' % (makelicense, stdout) showerror( 'Fehler', 'Errorcode: "%s"\nEin unbekannter Fehler ist aufgetreten!\nBitte senden Sie eine komplette Fehlerbeschreibung an "*****@*****.**"' % p.returncode)
print "Input Tre File Please:\n" treFile = askopenfilename() print "Input Geo File Please:\n" geoFile = askopenfilename() code2geo = {} for line in open(geoFile).read().splitlines(): geo, code = line.split('\t')[:2] code2geo[code] = geo outTre = '' ed = 0 for line in open(treFile).read().splitlines(): treLine = line pt = re.compile(r"([,\(]\s*)([A-Za-z]{3,10})(\s*:)") while 1: m = pt.search(treLine, ed) if m == None: break st = m.start() ed = m.end() before = m.group(1) code = m.group(2) after = m.group(3) ed = ed + len(code2geo[code]) - len(code) treLine = treLine.replace(before + code + after, before + code2geo[code] + after, 1) outTre += treLine + "\n" outFile = asksaveasfilename() open(outFile, 'w').write(outTre)
def AskSaveAsFilename(**kw): filename = filedialog.asksaveasfilename(**kw) return _FileNameChecker(filename)
def saveAs(self): print "Saving to File" fileName = tkFileDialog.asksaveasfilename(defaultextension=".sdk",filetypes=[("Sudoku", "*.sdk"),("All", "*")]) self.__lastFileName = fileName self.btn_save.config(state="active") self.save()
def save_game(): """Save the game""" filen = tkFileDialog.asksaveasfilename(filetypes=[("Save File", "sav")]) if filen: riskengine.save_game(filen)
def save_board_to_file(): filename = tkFileDialog.asksaveasfilename(defaultextension='.brd', filetypes=(('board files', '*.brd'), ('All files', '*.*'))) board.save_to_file(filename)
def save_as_jpg(initialdir=None, initialfile=None): filename = tkFileDialog.asksaveasfilename(initialdir=initialdir, \ initialfile=initialfile, \ filetypes=jpgtypes) return filename
def fileSaveAs(dialog_title): localRoot = tkinter.Tk() localRoot.withdraw() filename = tkFileDialog.asksaveasfilename(title=dialog_title) return filename
def file_save_as(self): file = tkFileDialog.asksaveasfilename()#self, filetypes=[('All files', '*')]) if file != '': self.filename = file self.file_save()
def _file_save_as(self): self.filename = tkFileDialog.asksaveasfilename(defaultextension='.txt') f = open(self.filename, 'w') f.write(self.get('1.0', 'end')) f.close()
def save_figure(self, initialfile=None, filetypes=None, *args): #----------------------------------------------- from tkFileDialog import asksaveasfilename from tkMessageBox import showerror #----------------------------------------------- if filetypes : sorted_filetypes = [] filetypes_supported = self.canvas.get_supported_filetypes() for filetype in filetypes : if filetypes_supported.has_key(filetype) : sorted_filetypes.append((filetype, filetypes_supported[filetype])) else : # as before filetypes = self.canvas.get_supported_filetypes().copy() default_filetype = self.canvas.get_default_filetype() # Tk doesn't provide a way to choose a default filetype, # so we just have to put it first default_filetype_name = filetypes[default_filetype] del filetypes[default_filetype] sorted_filetypes = filetypes.items() sorted_filetypes.sort() sorted_filetypes.insert(0, (default_filetype, default_filetype_name)) #----------------------------------------------- tk_filetypes = [ (name, '*.%s' % ext) for (ext, name) in sorted_filetypes] # adding a default extension seems to break the # asksaveasfilename dialog when you choose various save types # from the dropdown. Passing in the empty string seems to # work - JDH #defaultextension = self.canvas.get_default_filetype() defaultextension = '' initialdir = rcParams.get('savefig.directory', '') initialdir = os.path.expanduser(initialdir) #----------------------------------------------- if not initialfile : initialfile = self.canvas.get_default_filename() #----------------------------------------------- fname = asksaveasfilename( master=self.window, title='Save the figure', filetypes=tk_filetypes, defaultextension=defaultextension, initialdir=initialdir, initialfile=initialfile, ) if fname == "" or fname == (): #----------------------------------------------- return fname #----------------------------------------------- else: if initialdir == '': # explicitly missing key or empty str signals to use cwd rcParams['savefig.directory'] = initialdir else: # save dir for next time rcParams['savefig.directory'] = os.path.dirname(unicode(fname)) try: # This method will handle the delegation to the correct type self.canvas.print_figure(fname) except Exception as e: showerror("Error saving file", str(e)) #----------------------------------------------- return fname
if len(dirname ) > 0: print("You chose %s" % dirname ): elif dialog_mode=="file" # ======== Select a file for opening: root = Tkinter.Tk() file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file') if file != None: data = file.read() file.close() print "I got %d bytes from this file." % len(data) elif dialog_mode=="save" # ======== "Save as" dialog: myFormats = [ ('Windows Bitmap','*.bmp'),('Portable Network Graphics','*.png'), ('JPEG / JFIF','*.jpg'), ('CompuServer GIF','*.gif'), ] root = Tkinter.Tk() fileName = tkFileDialog.asksaveasfilename(parent=root,filetypes=myFormats ,title="Save the image as...") if len(fileName ) > 0: print("Now saving under %s" % nomFichier) ############################################################################################
# use all the options flag. could have -tk which causes it to import using tk, -in, -out # design all the settings so it works as pipe, or as files. # stltools --in=file.stl --out=fil1.stl -b/-a if --out missing then piping # stltools --tk does the following. # stltools --in=file.stl --stats prints bounding box etc. if __name__ == '__main__': import tkFileDialog fin = tkFileDialog.askopenfilename( defaultextension = '*.stl', filetypes = [('Stereolithography','*.stl'),('all files','*.*')], title = "Open STL") a = converter(fin) t = a.isascii and "Save as STL (Binary format)" or "Save as STL (ASCII format)" fout = tkFileDialog.asksaveasfilename( defaultextension = '*.stl', filetypes = [('Stereolithography','*.stl'),('all files','*.*')], title = t) a.convert(fout) # Example STL ascii file: # # solid # ... # facet normal 0.00 0.00 1.00 # outer loop # vertex 2.00 2.00 0.00 # vertex -1.00 1.00 0.00 # vertex 0.00 -1.00 0.00
import csv import Tkinter, Tkconstants, tkFileDialog from Tkinter import * root = Tk() root.baselink = tkFileDialog.askopenfilename(initialdir = "/",title = "Select ewmapa TXT",filetypes = (("all files","*.*"),)) root.csvlink = tkFileDialog.asksaveasfilename(initialdir = "/",title = "Select CSV name",defaultextension = ".csv",filetypes = (('Comma Separated values', '*.csv'),)) print root.baselink txt=open(root.baselink,"r") csvfile=open (root.csvlink,'w') fieldnames=['wkt','id','operat','typlinii','tekst','datamod','usermod','datautw','userutw',"warstwa"] spamwriter = csv.DictWriter(csvfile,fieldnames=fieldnames) spamwriter.writeheader() n=-1 for line in txt: if "**" in line: try: warstwa=txt.next() print(warstwa) except: pass elif " 20 5.9" in line: n+=1 splted=line.split() wsp1=str([splted[3],splted[2]]) wsp2=str([splted[5],splted[4]]) wkt=str(wsp1).strip("[',',']") wkt=wkt.replace("', '"," ")
def fixSourcesBySetup(logger, networklist, sourcelist, setup): warn = '' sources_to_save = [] scenarios_to_save = [] for sc, scenario in enumerate(setup): source_sce = scenario['source'] if source_sce['network'] not in listNetworks(logger, networklist): logger.set('New camera network (' + source_sce['network'] + ') found in setup, added the network.') warn += 'New camera network (' + source_sce[ 'network'] + ') found in setup, added the network.\n' i = 1 ids = [] for network in networklist: ids.append(network['id']) while len(ids) > 0 and str(i) in ids: i += 1 nname = source_sce['network'] networklist.append({ 'temporary': True, 'id': str(i), 'name': nname, 'protocol': 'LOCAL', 'host': None, 'username': None, 'password': None, 'file': path.join(SourceDir, validateName(nname).lower() + '.ini'), 'localfile': validateName(nname).lower() + '.ini' }) validnames = listSources(logger, sourcelist, source_sce['network']) for i, v in enumerate(validnames): validnames[i] = validateName(v).lower() if validateName(source_sce['name']).lower() not in validnames: logger.set('New camera (' + source_sce['name'] + ') found in setup, added it to the network \'' + source_sce['network'] + '\'.') warn += 'New camera (' + source_sce[ 'name'] + ') found in setup, added it to the network \'' + source_sce[ 'network'] + '\'.\n' sourcedict = deepcopy(source_sce) if source_sce['network'] not in sources_to_save: sources_to_save.append(source_sce['network']) sourcedict.update({ 'temporary': True, 'networkid': getSource(logger, networklist, source_sce['network'])['id'] }) sourcelist.append(sourcedict) setup[sc]['source'].update({'temporary': True}) scenarios_to_save.append(sc) if warn != '': if sysargv['prompt'] and tkMessageBox.askyesno( 'Changes in networks', warn + 'Do you want to make changes permanent?'): for n, network in enumerate(networklist): if 'temporary' in network and network['temporary']: del networklist[n]['temporary'] writeTSVx(NetworklistFile, networklist) for network in sources_to_save: for s, source in enumerate(sourcelist): if 'temporary' in source and source['temporary']: del sourcelist[s]['temporary'] sourcedict = getSources(logger, sourcelist, network, 'network') network = getSource(logger, networklist, network) if network['protocol'] == 'LOCAL': if tkMessageBox.askyesno( 'Save changes', 'Changes in be saved to the file: ' + network['file'] + '. Are you sure?'): writeTSVx(network['file'], sourcedict) else: tkMessageBox.showinfo( 'Save changes', 'Program now will export the CNIF. Upload it to the host \'' + network['host'] + '\' under directory \'' + path.split(network['file'])[0] + ' \'with the name \'' + path.split(network['file'])[1] + '\'. Mind that for HTTP connections, it might take some time until the updated file is readable.' ) file_opt = options = {} options['defaultextension'] = '.tsvx' options['filetypes'] = [ ('Extended tab seperated value files', '.tsvx'), ('all files', '.*') ] options['title'] = 'Set filename to export CNIF to...' ans = path.normpath( tkFileDialog.asksaveasfilename(**file_opt)) if ans != '' and ans != '.': writeTSVx(ans, sourcedict) for sc in scenarios_to_save: del setup[sc]['source']['temporary'] return (networklist, sourcelist, setup)
try: # builtin output builder mod, cls, name = outputclass outputclass = getattr( __import__('totalopenstation.output.' + mod, None, None, [cls]), cls) except ImportError, msg: showwarning( _('Import error'), _('Error loading the required output module: %s' % msg)) # no point in parsing before the output format has been imported parsed_data = inputclass(self.data) parsed_points = parsed_data.points output = outputclass(parsed_points) sd = tkFileDialog.asksaveasfilename(defaultextension='.%s' % of_lower) try: sd_file = open(sd, 'wb') except TypeError: showwarning(_("No output file specified"), _("No processing settings entered!\n")) else: sd_file.write(output.process()) sd_file.close() class PreferencesDialog(tkSimpleDialog.Dialog): '''A dialog to change preferences and options.'''
k]) - 8 * int(img[i, j, k]) value = int(img[i, j, k]) + -1 * discrete_laplacian if (value > 255): output[i, j, k] = 255 elif (value < 0): output[i, j, k] = 0 else: output[i, j, k] = value while (1): cv2.imshow('Sharpening Filter Image', output) c = cv2.waitKey(1) if c == 27: cv2.destroyAllWindows() break Tkinter.Tk().withdraw() # Close the root window out_path = tkFileDialog.asksaveasfilename() cv2.imwrite(out_path, output)
def calcCommand(unico, pendientes, mercurio, log): '''Callback for the "cross files" button that validates files and process them''' unico = unico.file.get() pendientes = pendientes.file.get() mercurio = mercurio.file.get() # Some file validation if not unico: tkMessageBox.showerror(u"No se encontró fichero", u"Seleccione un fichero único!") elif not pendientes: tkMessageBox.showerror( u"No se encontró fichero", u"Seleccione un fichero de pedidos pendientes!") elif not mercurio: tkMessageBox.showerror(u"No se encontró fichero", u"Seleccione un fichero mercurio!") elif 0 != common.readvalidate(unico): tkMessageBox.showerror( u"Problema de lectura", u"No se puede leer el fichero único! Pruebe con otro archivo.") elif 0 != common.readvalidate(pendientes): tkMessageBox.showerror( u"Problema de lectura", u"No se puede leer el archivo de pedidos pendientes! Pruebe con otro archivo." ) elif 0 != common.readvalidate(mercurio): tkMessageBox.showerror( u"Problema de lectura", u"No se puede leer el fichero mercurio! Pruebe con otro archivo.") # if all files are valid, procede else: # read destination of output tkMessageBox.showinfo( u'Fichero de cruces', u'Escoja la ubicación donde escribir el fichero de cruces.') outputext = ".xlsx" output = None output = tkFileDialog.asksaveasfilename( title="Seleccione la ubicación donde guardar el archivo final (%s)" % outputext, filetypes=[('Microsoft Excel 2007', '%s' % outputext)], defaultextension=outputext) if not output: tkMessageBox.showerror( "Error", u"Tiene que especificar un archivo!, vuelva a intentarlo escogiendo uno." ) elif not common.wincheckwriteperm(output): tkMessageBox.showerror( "Error", u"El archivo está bloqueado por otro programa! Vuelva a intentarlo cuando no esté bloqueado." ) else: try: programa_pedidos.processfiles(unico, pendientes, mercurio, output, log=lambda *args: log(*args)) except Exception as e: if os.isatty(sys.stdin.fileno()): traceback.print_exc() err = str(e).decode('utf-8') log("ERROR", err) functionmap = { 'writecrossxls': u"Error al escribir el archivo de cruce", 'parseCustomFile': u'Error al leer el archivo mercurio', 'xls2sqlite': lambda e: u'Error al leer el archivo %s' % e.file } tb = sys.exc_info()[2] errmsg = u'Se produjo un error al procesar los archivos' for t in traceback.extract_tb(tb): if t[2] in functionmap: r = functionmap[t[2]] if hasattr(r, "__call__"): errmsg = r(e) else: errmsg = r tkMessageBox.showerror( u"Fallo al procesar", errmsg + u'\n\nMensaje de error: %s' % err) return msg_exito = u'Proceso de cruce finalizado con éxito!' tkMessageBox.showinfo('Proceso finalizado', msg_exito) log(msg_exito)
def save_file_as(self): self.file_opt['title'] = 'Save file as...' self.filename = tkFileDialog.asksaveasfilename(**self.file_opt) self.write_file()