def runOpenFileDialog(self,title,filetypes,defaultextension,multiple=False): """Create and run an Tkinter open file dialog .""" # __pychecker__ = '--no-argsused' # defaultextension not used. initialdir = g.app.globalOpenDir or g.os_path_abspath(os.getcwd()) if multiple: # askopenfilenames requires Python 2.3 and Tk 8.4. version = '.'.join([str(sys.version_info[i]) for i in (0,1,2)]) if ( g.CheckVersion(version,"2.3") and g.CheckVersion(self.root.getvar("tk_patchLevel"),"8.4") ): files = tkFileDialog.askopenfilenames( title=title,filetypes=filetypes,initialdir=initialdir) # g.trace(files) return list(files) else: # Get one file and return it as a list. theFile = tkFileDialog.askopenfilename( title=title,filetypes=filetypes,initialdir=initialdir) return [theFile] else: # Return a single file name as a string. return tkFileDialog.askopenfilename( title=title,filetypes=filetypes,initialdir=initialdir)
def Operations(self, optionChoice): # File operations - calls to other modules to be implemented here # *************** file operations and other action calls to be implemented here *************** # # FILE OPERATION CALLS if optionChoice == 1: foo = None elif optionChoice == 2: self.filename = tkFileDialog.askopenfilename(filetypes=[("CSV", "*.csv")]) if self.filename != '': status_return, color, status_Done, donecolor = BioRad_CSV.main(self.filename, 'duplex') self.updateStatus(self.master, status_return, 1, 2000, color) if status_Done != '': def done_stat(): self.updateStatus(self.master, status_Done, 1, 3000, donecolor) self.master.after(5000, done_stat) elif optionChoice == 3: self.filename = tkFileDialog.askopenfilename(filetypes=[("CSV", "*.csv")]) if self.filename != '': status_return, color, status_Done, donecolor = BioRad_CSV.main(self.filename, 'singleplex') self.updateStatus(self.master, status_return, 1, 2000, color) if status_Done != '': def done_stat(): self.updateStatus(self.master, status_Done, 1, 3000, donecolor) self.master.after(5000, done_stat) else: print "INTERNAL ERROR: else condition inside Operations"
def engage(self, hideOrNot, extension): hidey = hideOrNot.get() ext = extension.get() if hidey == 0: imageFile = tkFileDialog.askopenfilename(title="Hiding: Choose Image File") # Get the image file from the user dataFile = tkFileDialog.askopenfilename(title="Hiding: Choose Data File") # Get the data file from the user errorCode = HerpHandler(hidey, imageFile, ext, dataFile) # Handle Operational Errors if errorCode == 1: tkMessageBox.showerror("Error", "The image does not match the chosen image type!") elif errorCode == 2: tkMessageBox.showerror("Error", "Too much data to fit") elif errorCode == 3: tkMessageBox.showerror("Error", "IOError: Could not open data file or image") elif errorCode == 4: tkMessageBox.showerror("Error", "IOError: Could not write to file") elif errorCode == 5: tkMessageBox.showerror("Error", "Out of Bounds Error") else: tkMessageBox.showinfo("Operation Complete", "Hiding Complete") else: imageFile = tkFileDialog.askopenfilename(title="Retrieving: Choose Image File") # Get the image file from the user errorCode = HerpHandler(hidey, imageFile, ext, None) # Handle Operational Errors if errorCode == 1: tkMessageBox.showerror("Error", "The image does not match the chosen image type!") elif errorCode == 2: tkMessageBox.showerror("Error", "Too much data to fit") elif errorCode == 3: tkMessageBox.showerror("Error", "IOError: Could not open data file or image") elif errorCode == 4: tkMessageBox.showerror("Error", "IOError: Could not write to file") elif errorCode == 5: tkMessageBox.showerror("Error", "Out of Bounds Error") else: tkMessageBox.showinfo("Operation Complete","Retrieval Complete")
def go(): window = Tkinter.Tk() window.withdraw() window.wm_title("tk-okienko") mg.vid1 = VideoCapture(tkFileDialog.askopenfilename(title="Wybierz wideo zewnętrzne", filetypes=mg.videoTypes)) mg.vid1LastFrame = mg.vid1.read()[1] mg.vid1LastFrameClean = numpy.copy(mg.vid1LastFrame) mg.vid2 = VideoCapture(tkFileDialog.askopenfilename(title="Wybierz wideo wewnętrzne", filetypes=mg.videoTypes)) namedWindow(mg.imgWindowName) setPoints(True) setMouseCallback(mg.imgWindowName, onMouseClick) imshow(mg.imgWindowName, mg.vid1LastFrame) waitKey(0) setMouseCallback(mg.imgWindowName, lambda a1, a2, a3, a4, a5: None) while True: innerFrame = mg.vid2.read()[1] fillPoly(mg.vid1LastFrameClean, numpy.array([[mg.p1, mg.p2, mg.p4, mg.p3]]), (0,0,0)) imshow("video", mg.vid1LastFrameClean+getTransformed(innerFrame)) mg.previousFrameClean = mg.vid1LastFrameClean ret, mg.vid1LastFrame = mg.vid1.read() mg.vid1LastFrameClean = numpy.copy(mg.vid1LastFrame) corners() if not ret: break key = waitKey(30) if key%256 == 27: break
def CMVDialog(self): import tkFileDialog import tkMessageBox try: import pygame as pg except ImportError: tkMessageBox.showerror('Error', 'This plugin requires the "pygame" module') return myFormats = [('Portable Network Graphics', '*.png'), ('JPEG / JFIF', '*.jpg')] try: image_file = tkFileDialog.askopenfilename(parent=self.root, filetypes=myFormats, title='Choose the contact map image file') if not image_file: raise except: tkMessageBox.showerror('Error', 'No Contact Map!') return myFormatsPDB = [('Protein Data Bank', '*.pdb'), ('MDL mol', '*.mol'), ('PyMol Session File', '*.pse')] try: pdb_file = tkFileDialog.askopenfilename(parent=self.root, filetypes=myFormatsPDB, title='Choose the corresponding PDB file') if not pdb_file: raise except: tkMessageBox.showerror('Error', 'No PDB file!') return name = cmd.get_unused_name('protein') cmd.load(pdb_file, name) contact_map_visualizer(image_file, name, 1, 0)
def open_list(self): """ opens a saved playlist playlists are stored as textfiles each record being "path","title" """ if self.options.initial_playlist_dir=='': self.filename.set(tkFileDialog.askopenfilename(defaultextension = ".csv", filetypes = [('csv files', '.csv')], multiple=False)) else: self.filename.set(tkFileDialog.askopenfilename(initialdir=self.options.initial_playlist_dir, defaultextension = ".csv", filetypes = [('csv files', '.csv')], multiple=False)) filename = self.filename.get() if filename=="": return self.options.initial_playlist_dir = '' ifile = open(filename, 'rb') pl=csv.reader(ifile) self.playlist.clear() self.track_titles_display.delete(0,self.track_titles_display.size()) for pl_row in pl: if len(pl_row) != 0: self.playlist.append([pl_row[0],pl_row[1],'','']) self.track_titles_display.insert(END, pl_row[1]) ifile.close() self.playlist.select(0) self.display_selected_track(0) return
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 load_ImageOnclicked(self): ########################################################################### ## Displaying input image. ########################################################################### global initial_im global ref global initial_depth ImageName = askopenfilename(initialdir="F:\UWA\GENG5511\simulation\images",title = "Choose an image file.") #Using try in case user types in unknown file or closes without choosing a file. try: with open(ImageName,'r') as UseFile: print (ImageName) except: print("No file exists") DepthName = askopenfilename(initialdir="F:\UWA\GENG5511\simulation\images") #Using try in case user types in unknown file or closes without choosing a file. try: with open(DepthName,'r') as UseFile: print (DepthName) except: print("No file exists") ref,initial_im=load_Image(ImageName) initial_depth=load_Depth(DepthName,ref,initial_im)
def de(): print "Select the encrypted file" Tk().withdraw() path_of_file_data_in_ = askopenfilename() path_of_de_data_in = open(path_of_file_data_in_, "r") de_data_in = path_of_de_data_in.read() path_of_de_data_in.close() print "Select the key" path_of_file_data_key_ = askopenfilename() path_of_de_key = open(path_of_file_data_key_, "r") de_key_in = path_of_de_key.read() path_of_de_key.close() de_xor_x = xor_en(de_data_in, ke=de_key_in) path_of_de_data_out = open("de/de_data.out", "w") path_of_de_data_out.write(de_xor_x) path_of_de_data_out.close() log_header_de= """Date: """ + str(now) + """ Encrypted Message: """ + str(de_data_in) + """ Key:"""+str(de_key_in)+""" Decrypted Message: """+ str(de_xor_x)+ """\n""" log_de = 'de/log.txt' log_data_de = open(log_de, "w") log_data_de.write(log_header_de + "\n" ) log_data_de.close() os.system("gedit de/log.txt de/de_data.out")
def openSTLFile(self): if self.printing: self.logger.logMsg("Cannot open a new file while printing") return if self.StlFile is None: fn = askopenfilename( filetypes=[("STL files", "*.stl"), ("G Code files", "*.gcode")], initialdir=self.settings.lastdirectory ) else: fn = askopenfilename( filetypes=[("STL files", "*.stl"), ("G Code files", "*.gcode")], initialdir=self.settings.lastdirectory, initialfile=os.path.basename(self.StlFile), ) if fn: self.settings.lastdirectory = os.path.dirname(os.path.abspath(fn)) self.settings.setModified() if fn.lower().endswith(".gcode"): self.StlFile = None self.loadgcode(fn) elif fn.lower().endswith(".stl"): self.StlFile = fn self.doSlice(fn) else: self.logger.logMsg("Invalid file type")
def browse_command(self, source): if source == 0: # Get the spec file location self.spec_file = tkFileDialog.askopenfilename(multiple=False, initialdir=self.default_path, filetypes=[("SUMA spec file", "*.spec")]) if self.spec_file: self.spec_var.set(self.spec_file) self.default_path = os.path.dirname(self.spec_file) elif source == 1: # Get the volume file location self.vol_file = tkFileDialog.askopenfilename(multiple=False, initialdir=self.default_path, filetypes=[("AFNI HEAD file", "*.HEAD"),]) if self.vol_file: self.vol_var.set(self.vol_file) self.default_path = os.path.dirname(self.vol_file) # ("AFNI BRIK file", "*.BRIK")]) # Remove the file extension # self.vol_file = os.path.splitext(self.vol_file)[0] elif source == 2: # Get the annot file location self.annot_file = tkFileDialog.askopenfilename(multiple=False, initialdir=self.default_path, filetypes=[("FreeSurfer annot file", "*.annot")]) if self.annot_file: self.annot_var.set(self.annot_file) self.default_path = os.path.dirname(self.annot_file)
def SelectFile(self, parent, defaultextension=None): if len(self.preferences.workSpaceFolder) > 0: return askopenfilename( parent=parent, initialdir=self.preferences.workSpaceFolder, defaultextension=defaultextension ) else: return askopenfilename(parent=parent, defaultextension=defaultextension)
def calibrate(poni_file=None, calibration_imagefile=None, dspace_file=None, wavelength=None, detector=None): """ Load the calibration file/make a calibration file """ pwd = os.getcwd() if poni_file is None: print 'Open PONI' poni_file = tkFileDialog.askopenfilename(defaultextension='.poni') if poni_file == '': # if prompt fail run calibration via pyFAI if calibration_imagefile is None: calibration_imagefile = tkFileDialog.askopenfilename( defaultextension='.tif') if dspace_file is None: dspace_file = tkFileDialog.askopenfilename() detector = detector if detector is not None else raw_input( 'Detector Name: ') wavelength = wavelength if wavelength is not None else raw_input( 'Wavelength in Angstroms: ') calibration_image_dir, calibration_image_name = os.path.split( calibration_imagefile) os.chdir(calibration_image_dir) subprocess.call(['pyFAI-calib', '-w', str(wavelength), '-D', str(detector), '-S', str(dspace_file), str(calibration_image_name)]) # get poni_file name make new poni_file poni_file = os.path.splitext(calibration_imagefile)[0] + '.poni' os.chdir(pwd) a = loadgeometry(poni_file) return a
def _openDialog(self): fpath = os.path.join( wtsettings.pathRes, self.entry.get()) fpath = os.path.abspath(fpath) dirname = os.path.dirname(fpath) dirname = os.path.abspath(dirname) # print "dirname",[dirname] newpath = "" if os.path.isfile(fpath): # print "isfile",[fpath] newpath = tkFileDialog.askopenfilename(initialfile= fpath, filetypes = self.ftypes) elif os.path.isdir(dirname): newpath =tkFileDialog.askopenfilename(initialdir= dirname, filetypes = self.ftypes) # print "isdir" else: newpath =tkFileDialog.askopenfilename(initialdir= wtsettings.pathRes, filetypes = self.ftypes) # print "no isdir" if newpath: num2res = len(os.path.normpath(os.path.abspath(wtsettings.pathRes)).split(os.path.sep)) newpath = os.path.normpath(newpath).split(os.path.sep) newpath = os.path.join( *newpath[num2res:] ) newpath = newpath.replace("\\","/") self.entry.delete(0, END) self.entry.insert(0, newpath) if self.old_value != newpath: self.onValueChangeEndByUser(self.old_value, newpath) self._updateImage()
def addSimulatorPath( self ): filename = "" if platform.system() == "Windows": filename = tkFileDialog.askopenfilename(parent=self.__root,initialdir="/",defaultextension=".exe",title='Pick a exe') else: filename = tkFileDialog.askopenfilename(parent=self.__root,initialdir="/",defaultextension=".app",title='Pick a app') self.__slVar.set( filename ) self.writeJson( "SimulatorPath", filename )
def _check_browse(self, index): if index == 0: return tkFileDialog.asksaveasfilename(defaultextension = FILES_JPT[0][1], filetypes = FILES_JPT) if index == 1: return tkFileDialog.askopenfilename(defaultextension = FILES_JPEG[0][1], filetypes = FILES_JPEG) if index == 2: return tkFileDialog.askopenfilename(defaultextension = FILES_PNG[0][1], filetypes = FILES_PNG) return FrameJpt._check_browse(index)
def openFile(): # Box Dialog to select an GOGODUCK file Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing if os.path.exists(os.path.expanduser('~/Downloads')): srs_GOGODUCK_URL=askopenfilename(filetypes=[("NetCDF file","*.nc")], initialdir=(os.path.expanduser('~/Downloads'))) else: srs_GOGODUCK_URL=askopenfilename(filetypes=[("NetCDF file","*.nc")]) return srs_GOGODUCK_URL
def get_textfile_name(): filename = tkFileDialog.askopenfilename() while filename and not re.search(r'.+\.txt', filename): print "error, you must choose a text (.txt) file" filename = tkFileDialog.askopenfilename() if not filename: print "goodbye, exiting hangman...\n\n\n\n" sys.exit(1) return filename
def extractBamFile(): print("Choose the data file which holds the information of the gene \ that you are looking for. Format gene name, chromosome, start position, end position.") Tk().withdraw() text_file_path = askopenfilename() print("Choose the BAM file that you are extracting reads from.") Tk().withdraw() bam_file_path = askopenfilename() sample_name = raw_input("What is the name of the sample the reads are coming from: ") sequence_size = raw_input("What is the length of each read's sequence: ") path = text_file_path.split('/') path.pop() path = '/'.join(path) path = '/' + path directory_path = path + '/' + sample_name if os.path.isdir(directory_path) == False: os.mkdir(directory_path) fin = open(text_file_path, 'r') for line in fin: try: gene_info = line.split("\t") gene_name = gene_info[0] chromosome = 'chr' + gene_info[1] start_position = gene_info[2] end_position = gene_info[3] samfile = pysam.Samfile(bam_file_path, "rb") iter = samfile.fetch(chromosome, int(start_position), int(end_position)) file_name = directory_path + '/' + gene_name + '.txt' gene_file = open(file_name, 'w') for x in iter: current_read = str(x) read_info = current_read.split("\t") read_start = read_info[3] read_end = str(int(read_info[3]) + int(sequence_size)) read_mapping_quality = read_info[4] read_sequence = read_info[9] selected_read_info = [read_start, read_end, read_mapping_quality, read_sequence] output_string = '\t'.join(selected_read_info) + '\n' gene_file.write(output_string) gene_file.close() except: print("Error Found") print("Done") fin.close() return;
def openFile(self): Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename(initialdir="E:/Images", title="choose your file", filetypes=(("jpeg files", "*.jpg"), ("all files", "*.*"))) location = askopenfilename() # show an "Open" dialog box and return the path to the selected file # radiSve(location) #dugmeSacuvaj = Button(root, text="Upisi podatke", width=20, height=5, command=lambda: prepoznavanje(ann, alphabet)) #dugmeSacuvaj.place(x=530, y=500) print(filename) return filename
def askpath(self): path = Config.settings.get_gamelog_path() if os.path.isfile(path): new_path = tkFileDialog.askopenfilename(initialfile=path, parent=self, filetypes=[('text files', '.txt')], title="Locate DwarfFortress/gamelog.txt") else: new_path = tkFileDialog.askopenfilename(initialdir=path, parent=self, filetypes=[('text files', '.txt')], title="Locate DwarfFortress/gamelog.txt") if os.path.isfile(new_path): Config.settings.set_gamelog_path(new_path) Config.settings.save() self.gamelog.connect()
def getFile(initialDir=""): root = tk.Tk() root.withdraw() if(initialDir != ""): file_path = tkFileDialog.askopenfilename(initialdir=initialDir) else: file_path = tkFileDialog.askopenfilename() root.destroy() return file_path
def filter_message(msg): if len(msg)>=1: if msg[0]=='~': if(msg[1:].split(' ')[0]=='quit'): return (-2 , 'disconnect') elif(msg[1:].split(' ')[0]=='file'): root = Tkinter.Tk() root.withdraw() file_path = '' try: file_path = tkFileDialog.askopenfilename() except: print "jir masuk" pass file_ = '' if file_path: file_name = file_path[file_path.rfind("/")+1:] #print file_name try : file_data = open(file_path,"r").read() file_ = "file\r\n"+file_name+"\r\n\r\n"+str(len(file_data))+"\r\n\r\n"+file_data+"\r\n\r\n\r\n" except: pass return (3,file_) elif msg[1:].split(' ')[0]=='whosonline': return (2,"user online") else: return (0,msg) elif msg[0]=='@': if len(msg)>1 and msg[1:].split(' ')[0] in proxy.list_user(): if len(msg.split(" ")) > 1 and msg.split(" ")[1] == "~file": file_path = '' try: root = Tkinter.Tk() root.withdraw() file_path = tkFileDialog.askopenfilename() except: file_path = '' file_ = '' if file_path: file_name = file_path[file_path.rfind("/")+1:] file_to = msg[1:].split(" ")[0] #print file_name file_data = open(file_path,"r").read() file_ = "fileto\r\n"+file_to+"\r\n\r\n"+file_name+"\r\n\r\n"+str(len(file_data))+"\r\n\r\n"+file_data+"\r\n\r\n\r\n" return (11,file_) return (1,msg.split("@")[1]) elif len(msg)>1 and msg[1:].split(' ')[0] not in proxy.list_user(): return (-1,msg.split("@")[1]) else: return (0,msg) else: return (0,msg) else: return (0,msg)
def _open(self, event=None): if self.path is None: self.file = askopenfilename(filetypes=(("database", "*.db"), ("All files", "*.*"))) else: self.file = askopenfilename(filetypes=(("database", "*.db"), ("All files", "*.*")), initialdir=self.path) if self.file == (): self._new() else: self.top.destroy()
def getname(self,initdir=None): """Calls tkFileDialog to allow the user to browse for a file, and then assigns this name to self.name""" if not initdir: path = askopenfilename(title="Choose file to process:",filetypes=self.a, initialdir=self.dir.get()) else: path = askopenfilename(title="Choose file to process:",filetypes=self.a, initialdir=initdir) if path: if self.validate(): self.update(path) self.dostuff()
def enter_filename(self): filename = askopenfilename(title="Choose an image") # show an "Open" dialog box and return the path to the selected file fileName, fileExtension = os.path.splitext(filename) while not fileExtension in ['.bmp', '.png']: # image not in right type, ask again showerror("Invalid file", "Please pick an image") filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file fileName, fileExtension = os.path.splitext(filename) # return filename for left image and right image right_image = filename.replace("cam1", "cam2") return filename, right_image
def openFile(self): self.db_entry.delete(0,tk.END) ftypes=[('sqlite files','*.sqlite'),('ALL files','*')] initialdir='~/.local/share/data/Mendeley Ltd./Mendeley Desktop' initialdir=os.path.expanduser(initialdir) if os.path.isdir(initialdir): filename=askopenfilename(filetypes=ftypes,initialdir=initialdir) else: filename=askopenfilename(filetypes=ftypes) self.db_entry.insert(tk.END,filename) if len(filename)>0: print('# <Menotexport>: Database file: %s' %filename) self.probeFolders()
def ask_openfile(initialfolder='.',title='Open',types=None): """Open a native file dialog that asks the user to choose a file. The path is returned as a string. Specify types in the format ['.bmp|Windows Bitmap','.gif|Gif image'] and so on. """ import tkFileDialog # for the underlying tkinter, Specify types in the format type='.bmp' types=[('Windows bitmap','.bmp')] if types!=None: aTypes = [(type.split('|')[1],type.split('|')[0]) for type in types] defaultExtension = aTypes[0][1] strFiles = tkFileDialog.askopenfilename(initialdir=initialfolder,title=title,defaultextension=defaultExtension,filetypes=aTypes) else: strFiles = tkFileDialog.askopenfilename(initialdir=initialfolder,title=title) return strFiles
def main(): idir = getcwd() OOT_ROM_NAME = askopenfilename(title="OoT Debug ROM",filetypes=[('N64 ROM files','*.z64')],initialdir = idir) if(not OOT_ROM_NAME): return MM_ROM_NAME = askopenfilename(title="Decompressed MM ROM",filetypes=[('N64 ROM files','*.z64')],initialdir = idir) if(not MM_ROM_NAME): return mmtmp = open(MM_ROM_NAME,"rb") mmtmp.seek(0,2) if ( mmtmp.tell() == 0x2000000 ): showerror(title = "uh lol", message = "Decompressed MM ROM, dummy!\nAborting port!") sys.exit(-1) argv__ = ['z64porter.py', OOT_ROM_NAME, MM_ROM_NAME] askaddress = True port_en = None while 1: argv_ = argv__[:] argv_ .append( askstring(title = "OoT scene", prompt = "Scene to replace in OoT (use 0x if hex):" )) if(not argv_[-1]): return argv_ .append( askstring(title = "MM scene", prompt = "Scene to port from MM (use 0x if hex):" )) if(not argv_[-1]): return if (askaddress): if (askyesno(title = "Address", message = "Insert at your own address?" )): argv_.append( "-o" ) addr_msg = "Address (hex) to insert port at:" if (port_en != None): addr_msg += "\nReccomended: %08X"%( port_en ) argv_.append( "0x%s" % (askstring(title = "Address", prompt = addr_msg ))) else: askaddress = False else: argv_.append("-o") argv_.append("0x%08X" % port_en) if (askyesno(title = "Safe mode", message = "Port in safe mode?" )): argv_.append( "-s" ) if (askyesno(title = "Music", message = "Use your own music value?" )): argv_.append( "-m" ) argv_.append(askstring(title = "Music", prompt = "Music value (use 0x if hex):" )) argv_.append("-q") try: port_st,port_en = port_scene( argv_ ) showinfo(title="Success", message="Scene ported successfully\nPort offsets:\n%08X - %08X"%(port_st,port_en)) except: showerror(title="Uhoh!", message="Failure :(.\nIf you opened this from a shell,\nplease report the error message from." ) break if not (askyesno(title = "Another", message = "Port another scene?" )): break
def main(): #this is the main part of the script. You can tell it is the main because it is called main. Tk().withdraw() #Not a full GUI titlePrep = "Choose your .iri file! the .csv" messagePrep = "This will add this IRI file to a new RSP file. The one ending in .CSV!!!" iriPath = askopenfilename(title = titlePrep, message = messagePrep)#show an open dialog box - This is for the IRI file. titlePrep2 = "Choose your RSP file that is associated with the chosen IRI file. It should end in .RSP" messagePrep2 = "This will create a new rsp file with the info from the IRI file." rspPath = askopenfilename(title = titlePrep2, message = messagePrep2)#show an open dialog box - This is for the RSP file. The RSP and IRI do not have exactly the same name, otherwise I would have made this a batch process. #Make a new rep_new file. rspbasename[1] should be changed to 'iri' but I did not know that until I completed everything. rspbasename = os.path.basename(rspPath).rsplit('.',1) newRSPpath = os.path.join(os.path.dirname(rspPath), ".".join([rspbasename[0]+"_new", rspbasename[1]])) #open the iri and rsp as 'r' read only. open the new one as 'w' write. iriFile = open(iriPath, 'r') rspFile = open(rspPath, 'r') newRSPFile = open(newRSPpath, 'w') # Put the iri file into a list. Probably not the most efficient way to do this, but I okay wit dat. iriList = list() for thisline in iriFile: thislinesplit = thisline.split(',') if thislinesplit[1] != thislinesplit[2]: #Column one and two in the iri file are the distances from the start and stop of the iri summary. For some reason, some of them had 0 distance - 1 and 2 were the same numbers instead of being 1/1000th different. iriList.append(thislinesplit) iriFile.close() #Write each line from the old rsp file to the newrspfile. n = 0 for line in rspFile: lineparts = line.split(',') if lineparts[0] == '5406': #lineparts[0] is the first item in the line. try: newRSPFile.write(', '.join(iriList[n]) + '\r') #Write the iri list to the new rsp file. Join the list together and separated by commas. I added the space for prettyness. except IndexError: pass #Go on if there is an error. This will make is so the new rsp file skips over the rest of the 5406 lines. n = n + 1 else: newRSPFile.write(line) rspFile.close() newRSPFile.close() #Tell the user that the script is complete. window = Tk() window.wm_withdraw() tkMessageBox.showinfo(title="The End", message = "The new RSP file is complete.")
@author: luan """ from mpegCodec import codec from mpegCodec.utils import frame_utils as futils import matplotlib.pylab as plt from Tkinter import Tk from tkFileDialog import askopenfilename import sys import numpy as np root = Tk() root.withdraw() fileName = askopenfilename(parent=root, title="Enter with a file name.").__str__() if fileName == '': sys.exit('Filename empty!') print("\nFile: " + fileName) name = fileName.split('/') print name name = name[-1] print name name = name.split('.')[-1] print name # In order to run the encoder just enter with a video file. # In order to run the decoder just enter with a output file (in the output directory). files = 0 # 0 - Runs all encoder modes for a given video (normal - 444 and 420, hvs - 444 and 420) # 1 - Runs encoder for a given video with the following setup.
def select_image(): # grab a reference to the image panels global panelB # open a file chooser dialog and allow the user to select an input # image path = tkFileDialog.askopenfilename() # ensure a file path was selected if len(path) > 0: # load the image from disk, convert it to grayscale, and detect # edges in it image = cv2.imread(path) if image is None: tkMessageBox.showerror("Error", "Not a valid image file") assert image is not None, "Not a valid image file" DATA[0] = np.copy(image) DATA[1] = None # Face Detector detector = dlib.get_frontal_face_detector() gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = detector(gray, 0) bound_boxes = [] for face in faces: #if there are faces (x, y, w, h) = (face.left(), face.top(), face.width(), face.height()) bound_boxes.append([x, y, w, h]) cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2) # OpenCV represents images in BGR order; however PIL represents # images in RGB order, so we need to swap the channels image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # convert the images to PIL format... image = Image.fromarray(image) # ...and then to ImageTk format image = ImageTk.PhotoImage(image) # if the panels are None, initialize them if panelB is None: # while the second panel will store the edge map panelB = Label(image=image) panelB.image = image panelB.pack(side="right", padx=10, pady=10) # otherwise, update the image panels else: # update the pannels panelB.configure(image=image) panelB.image = image def printcoord(event, bound_boxes, rect_boxes): global DATA any_face = False for i, bound in enumerate(bound_boxes): if is_in_boundbox(event.x, event.y, bound): DATA[1] = rect_boxes[i] any_face = True if not any_face: #clicked outside faces then not more swapping DATA[1] = None #mouseclick event panelB.bind("<Button 1>", lambda event: printcoord(event, bound_boxes, faces))
# second pass training, picks out objects identified in motion detection and now swparate them manually into yes and on training data import cv2 import numpy as np import os,sys import math as m import pandas as pd import Tkinter from tkFileDialog import askopenfilename #Open the video file which needs to be processed root = Tkinter.Tk() movieName = askopenfilename(filetypes=[("Video files","*")]) ## Don't forget to provide altitude information in below variable alt = input("Enter height of video(integer): ") sz=12 # work out size of box if box if 32x32 at 100m grabSize = int(m.ceil((100.0/alt)*sz)) #HD = os.getenv('HOME') #MOVIEDIR = HD + '/Documents/Backup/Phd/Analysis/Videos' #DATADIR = HD + '/Documents/Backup/Phd/Analysis/Codes' #TRACKDIR = DATADIR #+ '/tracked/' #LOGDIR = DATADIR + '/logs/' #FILELIST = HD + '/Documents/Backup/Phd/Analysis/Codes/textX.csv' #df = pd.read_csv(FILELIST)
def choosesource(): source = tkFileDialog.askopenfilename()
def _fbrowse(self, widget): 'Implement the "Browse" button for a file entry field.' name = tkFileDialog.askopenfilename() if name: widget.delete(0, Tk.END) widget.insert(Tk.INSERT, name)
def auxpeaks(self): self.gwindow.shiftsdat = tkFileDialog.askopenfilename( title="Load auxillary peaks", filetypes=(("Peak files", "*.dat"), ("all files", "*.*"))) self.gwindow.canvas.key_press_event('A')
def get_filename(): filename = File.askopenfilename() print filename
def file_load(self): self.file_name.set(tkFileDialog.askopenfilename()) in_name = self.file_name.get() dot_i = in_name.rfind('.') self.out_file_name.set(in_name[:dot_i] + ".new" + in_name[dot_i:])
def castep_file_load(self): self.castep_file_name.set(tkFileDialog.askopenfilename())
import matplotlib.pyplot as plt import csv import numpy as np import os, time #use Tkinter to open a file which we want from Tkinter import * import Tkinter, Tkconstants, tkFileDialog #open the file that we want cwd = os.getcwd() root = Tk() root.filename = tkFileDialog.askopenfilename(initialdir=cwd, title="Select file", filetypes=(("txt files", "*.txt"), ("jpeg files", "*.jpg"), ("all files", "*.*"))) f = open(root.filename, "r") root.withdraw() #read that file my_txt1 = root.filename.split('/')[-1].split('.txt')[0] text = f.read() #plotting t = [] c1 = [] c2 = [] c3 = [] v1 = []
def openFile(): # opens a dialog to get a single file logging.debug("Open File...") theFile = filedialog.askopenfilename() return theFile
def browsefile(): filename = askopenfilename(parent=top) f = open(filename) content3.set(filename)
mc.setBlock(x0 + x, y0 + y, z0 + z, b, d) print "done" # TODO: entities return corner1, corner2 if __name__ == '__main__': if len(argv) >= 2: path = argv[1] else: import Tkinter from tkFileDialog import askopenfilename master = Tkinter.Tk() master.attributes("-topmost", True) path = askopenfilename(filetypes=['schematic {*.schematic}'], title="Open") master.destroy() if not path: exit() mc = Minecraft() pos = mc.player.getTilePos() (corner0, corner1) = importSchematic(mc, path, pos.x, pos.y, pos.z, centerX=True, centerZ=True) mc.postToChat("Done drawing, putting player on top") y = corner1[1]
def askopenfile(self): self.filename = tkFileDialog.askopenfilename(initialdir="/home/pi") if self.filename.endswith('.mp3'): pygame.mixer.music.load(self.filename) else: self.track = pygame.mixer.Sound(self.filename)
import codecs import re from Tkinter import Tk from tkFileDialog import askopenfilename Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename( ) # show an "Open" dialog box and return the path to the selected file infile = codecs.open(filename, "r", "utf8") outfile = codecs.open("output.txt", "w", "utf8") file = infile.read() end = re.compile(ur'([\u0964]\s|[\u003F]\s|[\u0021]\s)', re.UNICODE) split_sent = end.split(file) i = 0 while (i < len(split_sent)): outfile.write(split_sent[i]) if (len(split_sent[i]) < 3): outfile.write("\n") i = i + 1 print("Done. Please check the file output.txt", i)
import Tkinter as tk import tkFileDialog from pdf2txt_pypdf2 import pdf2txt print "selecciona el pdf" root = tk.Tk() root.withdraw() filename = tkFileDialog.askopenfilename() filename = pdf2txt(filename) print "el texto quedo en {}".format(filename)
def select_encryption_file(top, workspace): file_opt = {} file_opt['initialdir'] = os.path.dirname(workspace) file_opt['title'] = 'Please select an AES-128 key file' return tkFileDialog.askopenfilename(**file_opt)
from tkFileDialog import askopenfilename import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FormatStrFormatter filename = askopenfilename() file = open(filename, 'r') filename2 = askopenfilename() if filename2.strip() == "": filename2 = "C:\Users\User\Desktop\Power Measurement Files\10dBm Direct Full Spectrum" input_power = .01 else: input_power = float( raw_input("What was the input power of the calibration?")) file2 = open(filename2, 'r') output = open( filename.split('/')[-1].split('.txt')[0] + '_Calibrated.txt', 'w') for line in file: line = line.split(', ') line2 = file2.readline().split(', ') if (line[0] != line2[0]): print 'Both sweeps must have the same range and step width.' break output.write(line[0] + ', ' + str(float(line[1]) * float(line2[1]) / input_power) + '\n')
parser.add_argument('-p', '--passcode', default=None, type=passcode, help='register_code,email_or_deviceid') parser.add_argument("filename", nargs='?', help="mdx file name") args = parser.parse_args() # use GUI to select file, default to extract if not args.filename: import Tkinter import tkFileDialog root = Tkinter.Tk() root.withdraw() args.filename = tkFileDialog.askopenfilename(parent=root) args.extract = True if not os.path.exists(args.filename): print("Please specify a valid MDX/MDD file") base, ext = os.path.splitext(args.filename) # read mdx file if ext.lower() == os.path.extsep + 'mdx': mdx = MDX(args.filename, args.encoding, args.substyle, args.passcode) if type(args.filename) is unicode: bfname = args.filename.encode('utf-8') else: bfname = args.filename print('======== %s ========' % bfname)
def dataConfigBrowser(self): """File selector for database info""" self.dbConfigFileName.set(askopenfilename())
def choosedest(): dest = tkFileDialog.askopenfilename()
def load(*args, **kwargs): """ This function attempts to determine the base data type of a filename or other set of arguments by calling :meth:`yt.data_objects.api.Dataset._is_valid` until it finds a match, at which point it returns an instance of the appropriate :class:`yt.data_objects.api.Dataset` subclass. """ if len(args) == 0: try: from yt.extern.six.moves import tkinter import tkinter, tkFileDialog except ImportError: raise YTOutputNotIdentified(args, kwargs) root = tkinter.Tk() filename = tkFileDialog.askopenfilename(parent=root, title='Choose a file') if filename != None: return load(filename) else: raise YTOutputNotIdentified(args, kwargs) candidates = [] args = [ os.path.expanduser(arg) if isinstance(arg, str) else arg for arg in args ] valid_file = [] for argno, arg in enumerate(args): if isinstance(arg, str): if os.path.exists(arg): valid_file.append(True) elif arg.startswith("http"): valid_file.append(True) else: if os.path.exists( os.path.join(ytcfg.get("yt", "test_data_dir"), arg)): valid_file.append(True) args[argno] = os.path.join( ytcfg.get("yt", "test_data_dir"), arg) else: valid_file.append(False) else: valid_file.append(False) if not any(valid_file): try: from yt.data_objects.time_series import DatasetSeries ts = DatasetSeries.from_filenames(*args, **kwargs) return ts except YTOutputNotIdentified: pass mylog.error("None of the arguments provided to load() is a valid file") mylog.error("Please check that you have used a correct path") raise YTOutputNotIdentified(args, kwargs) for n, c in output_type_registry.items(): if n is None: continue if c._is_valid(*args, **kwargs): candidates.append(n) # convert to classes candidates = [output_type_registry[c] for c in candidates] # Find only the lowest subclasses, i.e. most specialised front ends candidates = find_lowest_subclasses(candidates) if len(candidates) == 1: return candidates[0](*args, **kwargs) if len(candidates) == 0: if ytcfg.get("yt", "enzo_db") != '' \ and len(args) == 1 \ and isinstance(args[0], str): erdb = EnzoRunDatabase() fn = erdb.find_uuid(args[0]) n = "EnzoDataset" if n in output_type_registry \ and output_type_registry[n]._is_valid(fn): return output_type_registry[n](fn) mylog.error("Couldn't figure out output type for %s", args[0]) raise YTOutputNotIdentified(args, kwargs) mylog.error("Multiple output type candidates for %s:", args[0]) for c in candidates: mylog.error(" Possible: %s", c) raise YTOutputNotIdentified(args, kwargs)
def selectFile(): global filename filename = filed.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("csv files","*.csv"),("all files","*.*"))) tk.Label(root,text=filename).place(relx=.5, rely=.5, anchor="c") t1 = Thread(target=callPredict(filename)) t1.start()
vetoConfig = True if(not vetoConfig): uinput = raw_input(" > (Int) [2 ^ " + str(res_expo) + " = " + str(2**res_expo) + "] Resolution: 2 to the power of: ") if uinput != "": res_expo = int(uinput) #Set the resolution MainCL.initHostArrays(res_expo) if(not vetoConfig): #Have the user select one of the kernel automata rules ruleFName = tfd.askopenfilename(initialdir="./RuleKernels", title="Select Kernel Rule (*.cl)") usePreset = raw_input(" > Use preset configuration? (Y/N): ") #Load the selected kernel print " > LOADING KERNEL" MainCL.kAutomata = MainCL.loadProgram(ruleFName) #Randomly seed host array MainCL.seed(seed_strength) if(not vetoConfig): if usePreset == "N" or usePreset == "n": #Query user about seeding the initial cell configurations SeedType = raw_input(" > Seed from bitmap file? (Y/N): ") if SeedType != "" and SeedType != "n" and SeedType != "N": #Seed from image
if __name__ == '__main__': if len(sys.argv) == 1: print('') print( 'USAGE: {} <participant data file> <med code effects file>'.format( os.path.basename(sys.argv[0]))) print("""'Creates total anti-cholinergic burden score per participants. 'First two columns should be: pupalz_id, redcap_event_name 'Medcodes in format dXXXXX should be contained in columnes named medN_code 'where N ranges from 1 to the total number of medications taken. Creates 'a file named PupAlz_AnticholBurden_<date>.csv in the same directory 'as input file.""") print('') root = tkinter.Tk() root.withdraw() # Select files to process subjfile = filedialog.askopenfilename( parent=root, title='Choose file with participant data', filetypes=(("csv files", "*.csv"), ("all files", "*.*"))) effectfile = filedialog.askopenfilename( parent=root, title='Choose file with medication effects', filetypes=(("csv files", "*.csv"), ("all files", "*.*"))) main(subjfile, effectfile) else: subjfile = sys.argv[1] effectfile = sys.argv[2] main(subjfile, effectfile)
def askopenfilename(**options): if _zenity_available: return _zenity_file_selection(**options).show(ztype='o') return tkFileDialog.askopenfilename(**options)
def openFile(): fileName = tkFileDialog.askopenfilename(initialdir="./dataset") app.fileName.set(fileName)
TKwindows.tk.call('namespace', 'import', '::tk::dialog::file::') except: pass try: TKwindows.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1') except: pass try: TKwindows.tk.call('set', '::tk::dialog::file::showHiddenVar', '0') except: pass TKwindows.update() #intercatively choose input NIFTI file InputFile = askopenfilename(title="Choose NIFTI file", filetypes=[("NIFTI files", ('*.nii', '*.NII', '*.nii.gz', '*.NII.GZ'))]) if InputFile == "": print('ERROR: No input file specified') sys.exit(2) InputFile = os.path.abspath(InputFile) TKwindows.update() try: win32gui.SetForegroundWindow(win32console.GetConsoleWindow()) except: pass #silent dirname = os.path.dirname(InputFile) basename = os.path.basename(InputFile) basename = os.path.splitext(basename)[0] basename = os.path.splitext(basename)[0] basename = basename[0:basename.rfind('_MAG')]
import numpy as np import open3d as o3d import matplotlib.pyplot as plt from itertools import chain from Tkinter import * from tkFileDialog import askopenfilename file_path_string = askopenfilename() print("**********************************************") print("Import the point cloud data saved in npy file " + str(file_path_string)) fileformat = ".npy" data = np.load(file_path_string ) label_file_path_string = askopenfilename() label_file = open(label_file_path_string, "r") label_lines = label_file.read() label_lines = label_lines.split("\n") if (len(label_lines)> 0): print("file is valid " + str(len(label_lines)) + " " + label_file_path_string) object_to_draw = [] for index, label_lines in enumerate(label_lines): label_segment = label_lines.split() if (len(label_segment)> 0): typeObject = label_segment[0] h = float(label_segment[8]) d = float(label_segment[9]) l = float(label_segment[10]) y = float(label_segment[11]) * (-1.0)
def setcombos(self): filename = askopenfilename(**self.fileopenoptions) self.combos.set(filename)