我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用wx.FileDialog()。
def Open(self, e): openFileDialog = wx.FileDialog( self, "Open Log file", "", "", "log files (*.mi2log) |*.mi2log| All files |*.*", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST | wx.FD_MULTIPLE) if (openFileDialog.ShowModal() == wx.ID_OK): # print 'Selected %s' %openFileDialog.GetPath() print 'Selected %s' % openFileDialog.Paths try: self.grid.ClearGrid() # thread.start_new_thread(openFile,(openFileDialog.GetPath(),)) # t = Thread(target = self.openFile, args=(openFileDialog.GetPath(),self.selectedTypes)) t = Thread( target=self.openFile, args=( openFileDialog.Paths, self.selectedTypes)) self.progressDialog = ProgressDialog(self) t.start() self.progressDialog.ShowModal() if len(openFileDialog.Paths) == 1: self.SetTitle(openFileDialog.GetPath()) else: self.SetTitle( "Multiple files in " + openFileDialog.Directory) except e: print "Error while opening file.", e # if (random() > 0.5): # self.SetupGrid(self.data1) # else: # self.SetupGrid(self.data2)
def doExport(self, event): dlg = wx.FileDialog(self, "Save to file:", ".", "", "Text (*.txt)|*.txt", wx.SAVE|wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: i = dlg.GetFilterIndex() if i == 0: # Text format try: f = open(dlg.GetPath(), "w") f.write("# Date, From, SerivceCenter, Message\n") for i in self.itemDataMap.keys(): entry = self.itemDataMap[i] f.write('%s,%s,%s,%s\n' % (entry[1], entry[2], entry[4].smsc, entry[3])) f.close() pySIMmessage(self, "SMS export to file was successful\n\nFilename: %s" % dlg.GetPath(), "Export OK") except: pySIMmessage(self, "Unable to save your SMS messages to file: %s" % dlg.GetPath(), "Export error") #print_exc() dlg.Destroy()
def saveCap(self): cap = self.src.getEEGSecs(self.getSessionTime(), filter=False) saveDialog = wx.FileDialog(self, message='Save EEG data.', wildcard='Pickle (*.pkl)|*.pkl|All Files|*', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) try: if saveDialog.ShowModal() == wx.ID_CANCEL: return cap.saveFile(saveDialog.GetPath()) except Exception: wx.LogError('Save failed!') raise finally: saveDialog.Destroy()
def captureImage(self, event=None): ## Parts borrowed from backends_wx.py from matplotlib # Fetch the required filename and file type. filetypes, exts, filter_index = self.canvas._get_imagesave_wildcards() default_file = self.canvas.get_default_filename() dlg = wx.FileDialog(self, "Save to file", "", default_file, filetypes, wx.SAVE|wx.OVERWRITE_PROMPT) dlg.SetFilterIndex(filter_index) if dlg.ShowModal() == wx.ID_OK: dirname = dlg.GetDirectory() filename = dlg.GetFilename() format = exts[dlg.GetFilterIndex()] basename, ext = os.path.splitext(filename) if ext.startswith('.'): ext = ext[1:] if ext in ('svg', 'pdf', 'ps', 'eps', 'png') and format!=ext: #looks like they forgot to set the image type drop #down, going with the extension. format = ext self.canvas.print_figure( os.path.join(dirname, filename), format=format)
def beforeStop(self): if not 'practice' in self.protocol: cap = self.src.getEEGSecs(time.time() - self.startTime, filter=False) fileName = self.subjectTextCtrl.GetValue() + '-' +\ self.protocol.replace(' ', '-') + '.pkl' saveDialog = wx.FileDialog(self, message='Save EEG data.', wildcard='Pickle (*.pkl)|*.pkl|All Files|*', defaultFile=fileName, style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) try: if saveDialog.ShowModal() == wx.ID_CANCEL: return cap.saveFile(saveDialog.GetPath()) except Exception: wx.LogError('Save failed!') raise finally: saveDialog.Destroy()
def saveMessages(self, event=None): """Save the message log to file. """ saveDialog = wx.FileDialog(self.scrolledPanel, message='Save Message Log', wildcard='Text Files (*.txt)|*.txt|All Files|*', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) try: if saveDialog.ShowModal() == wx.ID_CANCEL: return with open(saveDialog.GetPath(), 'w') as fileHandle: fileHandle.write(self.messageArea.GetValue()) except Exception as e: wx.LogError('Save failed!') raise finally: saveDialog.Destroy()
def loadFile(self, event=None): openFileDialog = wx.FileDialog(None, message='Load EEG data.', wildcard='JSON (*.json)|*.json|All Files|*', style=wx.FD_OPEN) try: if openFileDialog.ShowModal() == wx.ID_CANCEL: return wx.ID_CANCEL except Exception: wx.LogError('Save failed!') raise finally: openFileDialog.Destroy() cap = eeg.EEGFromJSON(openFileDialog.GetPath(), protocol='3minutes') self.replayData = cap.data self.setSampRate(cap.getSampRate()) self.setChans(cap.getChanNames())
def OpenSource(self, event): # wxGlade: MainFrame.<event_handler> dlg = wx.FileDialog( self, message="Choose Image", wildcard="All files (*.*)|*.*", style=wx.OPEN | wx.CHANGE_DIR ) if dlg.ShowModal() == wx.ID_OK: paths = dlg.GetPaths() for path in paths: self.EnumerateSource(path) print(' %s\n' % path) dlg.Destroy() event.Skip()
def OnLoadMesh(self, evt): dlg = wx.FileDialog(self, "Choose a file", ".", "", "OFF files (*.off)|*.off|TOFF files (*.toff)|*.toff|OBJ files (*.obj)|*.obj", wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetFilename() dirname = dlg.GetDirectory() filepath = os.path.join(dirname, filename) print dirname self.glcanvas.mesh = PolyMesh() print "Loading mesh %s..."%filename self.glcanvas.mesh.loadFile(filepath) self.glcanvas.meshCentroid = self.glcanvas.mesh.getCentroid() self.glcanvas.meshPrincipalAxes = self.glcanvas.mesh.getPrincipalAxes() print "Finished loading mesh" print self.glcanvas.mesh self.glcanvas.initMeshBBox() self.glcanvas.clearAllSelections() self.glcanvas.Refresh() dlg.Destroy() return
def OnGenerateProgramMenu(self, event): dialog = wx.FileDialog(self, _("Choose a file"), os.getcwd(), self.Controler.GetProgramFilePath(), _("ST files (*.st)|*.st|All files|*.*"), wx.SAVE | wx.CHANGE_DIR) if dialog.ShowModal() == wx.ID_OK: filepath = dialog.GetPath() message_text = "" header, icon = _("Done"), wx.ICON_INFORMATION if os.path.isdir(os.path.dirname(filepath)): program, errors, warnings = self.Controler.GenerateProgram(filepath) message_text += "".join([_("warning: %s\n") % warning for warning in warnings]) if len(errors) > 0: message_text += "".join([_("error: %s\n") % error for error in errors]) message_text += _("Can't generate program to file %s!") % filepath header, icon = _("Error"), wx.ICON_ERROR else: message_text += _("Program was successfully generated!") else: message_text += _("\"%s\" is not a valid folder!") % os.path.dirname(filepath) header, icon = _("Error"), wx.ICON_ERROR message = wx.MessageDialog(self, message_text, header, wx.OK | icon) message.ShowModal() message.Destroy() dialog.Destroy()
def getpath(title, filt, k, para=None): """Get the defaultpath of the ImagePy""" dpath = manager.ConfigManager.get('defaultpath') if dpath ==None: dpath = root_dir # './' dic = {'open':wx.FD_OPEN, 'save':wx.FD_SAVE} dialog = wx.FileDialog(curapp, title, dpath, '', filt, dic[k]) rst = dialog.ShowModal() path = None if rst == wx.ID_OK: path = dialog.GetPath() dpath = os.path.split(path)[0] manager.ConfigManager.set('defaultpath', dpath) if para!=None:para['path'] = path dialog.Destroy() return rst if para!=None else path
def do(self): #app = wx.PySimpleApp(0) wcd="Excel Files(*.xls)|*.xls|" dir = "/home" save_dlg = wx.FileDialog(self.parent, message='Choose File to be Imported', defaultDir=dir, defaultFile= '', wildcard=wcd, style=wx.OPEN) if save_dlg.ShowModal() == wx.ID_OK: path = save_dlg.GetPath() self.book = open_workbook(path) self.current_sheet=self.book.sheet_by_index(0) self.rown=self.current_sheet.nrows self.DB=db_operations() self.write_to_db() save_dlg.Destroy() print "extd"
def OnLoadMesh(self, evt): dlg = wx.FileDialog(self, "Choose a file", ".", "", "OFF files (*.off)|*.off|TOFF files (*.toff)|*.toff|OBJ files (*.obj)|*.obj", wx.OPEN) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetFilename() dirname = dlg.GetDirectory() filepath = os.path.join(dirname, filename) print dirname self.glcanvas.mesh = PolyMesh() print "Loading mesh %s..."%filename self.glcanvas.mesh.loadFile(filepath) self.glcanvas.meshCentroid = self.glcanvas.mesh.getCentroid() self.glcanvas.meshPrincipalAxes = self.glcanvas.mesh.getPrincipalAxes() print "Finished loading mesh" print self.glcanvas.mesh self.glcanvas.initMeshBBox() self.glcanvas.Refresh() dlg.Destroy() return
def on_open(self, event): """ Recursively loads a KiCad schematic and all subsheets """ #self.save_component_type_changes() open_dialog = wx.FileDialog(self, "Open KiCad Schematic", "", "", "Kicad Schematics (*.sch)|*.sch", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if open_dialog.ShowModal() == wx.ID_CANCEL: return # Load Chosen Schematic print("opening File:", open_dialog.GetPath()) # Store the path to the file history self.filehistory.AddFileToHistory(open_dialog.GetPath()) self.filehistory.Save(self.config) self.config.Flush() self.load(open_dialog.GetPath())
def OnTBLoad(self, event): if self.running: rng = True self.OnTBStart() else: rng = False dlg = wx.FileDialog(None, "Open Spectrum", os.getcwd(), "", "*.*", wx.OPEN) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetPath() # set new working directory directory = os.path.split(filename) if not os.path.isdir(filename): os.chdir(directory[0]) # save file tmpx, tmpy = np.loadtxt(filename, unpack=True) # add to plot window self.addLine(tmpx, tmpy) dlg.Destroy() if rng: self.OnTBStart()
def on_save_as(self): if self.get_project_filename(): dir_name, file_name = os.path.split(self.get_project_filename()) style = wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT wildcard = "Arquivo de projeto do GRIPy (*.pgg)|*.pgg" fdlg = wx.FileDialog(self.GetTopWindow(), 'Escolha o arquivo PGG', #dir_name, file_name, wildcard=wildcard, style=style ) if fdlg.ShowModal() == wx.ID_OK: file_name = fdlg.GetFilename() dir_name = fdlg.GetDirectory() if not file_name.endswith('.pgg'): file_name += '.pgg' disableAll = wx.WindowDisabler() wait = wx.BusyInfo("Saving GriPy project. Wait...") self.save_project_data(os.path.join(dir_name, file_name)) del wait del disableAll fdlg.Destroy()
def on_open(*args, **kwargs): wildcard = "Arquivo de projeto do GRIPy (*.pgg)|*.pgg" try: fdlg = wx.FileDialog(wx.App.Get().GetTopWindow(), 'Escolha o arquivo PGG', wildcard=wildcard, style=wx.FD_OPEN|wx.FD_FILE_MUST_EXIST ) if fdlg.ShowModal() == wx.ID_OK: file_name = fdlg.GetFilename() dir_name = fdlg.GetDirectory() fdlg.Destroy() else: fdlg.Destroy() return fullfilename = os.path.join(dir_name, file_name) gripy_app = wx.App.Get() gripy_app.load_project_data(fullfilename) except Exception: raise
def onOpen(self, evt=None): """This method opens an existing file""" dlg = wx.FileDialog( self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="", wildcard="*.json", style=wx.OPEN | wx.CHANGE_DIR ) # Show the dialog and retrieve the user response. If it is the OK response, # process the data. if dlg.ShowModal() == wx.ID_OK: # This returns a Python list of files that were selected. path = dlg.GetPath() print "I'd be opening file in onOpen ", path self.add_book.load_from_file(filename=path) else : print "The file dialog was canceled" dlg.Destroy()
def OnOpen(self, event): openFileDialog = wx.FileDialog(self, "Open i3 Config file", os.path.expanduser("~/.i3/"), "","i3 Config file |*", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) if openFileDialog.ShowModal() == wx.ID_CANCEL: return cfg = Config(self.messager,openFileDialog.GetPath()) self.LoadConfig(cfg)
def chooseSessionFile(self, e): wildcard = "Save file (*.txt)|*.txt|" \ "All files (*.*)|*.*" dlg = wx.FileDialog(self, message="Open configuration ...", defaultDir=os.getcwd(), defaultFile="", wildcard=wildcard, style=wx.OPEN) if dlg.ShowModal() == wx.ID_OK: self.path.SetValue(dlg.GetPath()) dlg.Destroy() self.FitInside() # Cette fonction permet aux préférences de se mettre à jour même si on ne les a pas changées dans la fenêtre de configuration initiale.
def onOpen(self,event): print "Open" fd = wx.FileDialog(self,style=wx.FD_OPEN) fd.ShowModal() self.filename = fd.GetPath() print "On Open...",self.filename self.openCSVFile(self.filename)
def onSaveAs(self,event): fd = wx.FileDialog(self,message="Save the coordinates as...",style=wx.FD_SAVE, wildcard="Comma separated value (*.csv)|*.csv") fd.ShowModal() self.filename = fd.GetPath() self.save(self.filename)
def OnOpenEtotV(self, event): wildcard = "dat file (*.dat)|*.dat|" \ "All files (*)|*" dialog = wx.FileDialog(None, "Choose a file with total energies", os.getcwd(),"", wildcard) if dialog.ShowModal() == wx.ID_OK: try: fname = dialog.GetPath() self.V, self.E = read_EtotV(fname) self.IsEtotVRead = True self.SetStatusText("E_tot(V) file "+fname+" read") except: wx.MessageBox("Something wrong while opening the E_tot file... not loaded.", "", wx.OK | wx.ICON_EXCLAMATION, self) dialog.Destroy()
def doExport(self, event): export_count = 0 dlg = wx.FileDialog(self, "Save to file:", ".", "", "Text (*.txt)|*.txt", wx.SAVE|wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: i = dlg.GetFilterIndex() if i == 0: # Text format try: f = open(dlg.GetPath(), "w") f.write('# "Name", Number\n') for i in range(self.listCtrl.GetItemCount()): f.write('"%s",%s\n' % (self.getColumnText(i,0), self.getColumnText(i,1))) export_count += 1 f.close() pySIMmessage(self, "Exported %d phonebook contacts\n\nFilename: %s" % (export_count, dlg.GetPath()), "Export OK") except: print_exc() pySIMmessage(self, "Unable to save your phonebook to file: %s" % dlg.GetPath(), "Export error") # elif i == 1: # Excel document # try: # xl = win32com.client.Dispatch("Excel.Application") # xl.Workbooks.Add() # xl.Cells(1,1).Value = "Name" # xl.Cells(1,2).Value = "Number" # for i in range(self.listCtrl.GetItemCount()): # row = i + 2 # xl.Cells(row,1).Value = self.getColumnText(i,0) # xl.Cells(row,2).Value = self.getColumnText(i,1) # export_count += 1 # xl.ActiveWorkbook.SaveAs(dlg.GetPath()) # xl.ActiveWorkbook.DisplayAlerts = 0 # #xl.Saved = 1 # xl.Quit() # pySIMmessage(self, "Exported %d phonebook contacts\n\nFilename: %s" % (export_count, dlg.GetPath()), "Export OK") # except: # print_exc() # pySIMmessage(self, "Unable to save your phonebook to file: %s" % dlg.GetPath(), "Export error") dlg.Destroy()
def do_open(self, evt): dlg = wx.FileDialog( self, message="Choose a file", defaultDir=os.getcwd(), defaultFile="invoice.csv", wildcard="CSV Files (*.csv)|*.csv", style=wx.OPEN ) if dlg.ShowModal() == wx.ID_OK: # This returns a Python list of files that were selected. self.filename = dlg.GetPaths()[0] dlg.Destroy() self.SetTitle(self.filename + " - " + self.title) self.do_new() tmp = [] for lno, linea in enumerate(open(self.filename).readlines()): if DEBUG: print "processing line", lno, linea args = [] for i,v in enumerate(linea.split(";")): if not v.startswith("'"): v = v.replace(",",".") else: v = v#.decode('latin1') if v.strip()=='': v = None else: v = eval(v.strip()) args.append(v) tmp.append(args) # sort by z-order (priority) for args in sorted(tmp, key=lambda t: t[-1]): if DEBUG: print args self.create_elements(*args) self.diagram.ShowAll( 1 ) # return True
def OnButtonSaveAs(self, msg): if not self.model.status: wx.MessageBox('No export file has been successfully loaded yet!') return dialog = wx.FileDialog( self, 'Save As ...', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) result = dialog.ShowModal() if result != wx.ID_OK: return # Show filedialog and get value self.model.save(dialog.GetPath())
def saveResultText(self, resultText): saveDialog = wx.FileDialog(self, message='Save Result Text.', wildcard='Text (*.txt)|*.txt|All Files|*', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) try: if saveDialog.ShowModal() == wx.ID_CANCEL: return with open(saveDialog.GetPath(), 'w') as fd: fd.write(resultText) except Exception: wx.LogError('Save failed!') raise finally: saveDialog.Destroy()
def saveCap(self): cap = self.src.getEEGSecs(self.getSessionTime(), filter=False) saveDialog = wx.FileDialog(self, message='Save EEG data.', wildcard='Pickle (*.pkl)|*.pkl|All Files|*', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) try: if saveDialog.ShowModal() == wx.ID_CANCEL: return cap.saveFile(saveDialog.GetPath()) except Exception: wx.LogError('Save failed!') raise finally: saveDialog.Destroy() ##def decimate(self, cap): ## #cap = cap.demean().bandpass(0.5, 10.0, order=3) ## cap = cap.copy().demean().bandpass(0.5, 12.0, order=3) ## # kind of a hack XXX - idfah ## if cap.getSampRate() > 32.0: ## decimationFactor = int(np.round(cap.getSampRate()/32.0)) ## cap = cap.downsample(decimationFactor) ## return cap
def saveFile(self): self.refresh() saveDialog = wx.FileDialog(self, message='Save Image', wildcard='Portable Network Graphics (*.png)|*.png|All Files|*', style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) try: if saveDialog.ShowModal() != wx.ID_CANCEL: img = self.drawingBuffer.ConvertToImage() img.SaveFile(saveDialog.GetPath(), wx.BITMAP_TYPE_PNG) except Exception as e: wx.LogError('Save failed!') raise finally: saveDialog.Destroy()
def on_browser_button(self, evt): cur_entry = self.current_textctrl_GetValue() if len(cur_entry) == 0: cur_entry = self.default_entry cur_entry = os.path.abspath(os.path.expanduser(cur_entry)) cur_entry_parts = [a for a in ['/'] + cur_entry.split('/') if len(a) > 0] while (len(cur_entry_parts) >= 1 and not (os.path.isdir(os.path.join(*cur_entry_parts)) or os.path.isfile(os.path.join(*cur_entry_parts)))): cur_entry_parts = cur_entry_parts[:-1] if len(cur_entry_parts) > 1: cur_entry = os.path.join(*cur_entry_parts) else: cur_entry = os.path.expanduser('~') if os.path.isdir(cur_entry): cur_basename = '' cur_dirname = cur_entry else: cur_basename = os.path.basename(cur_entry) cur_dirname = os.path.dirname(cur_entry) if self.is_files_not_dirs: dlg = wx.FileDialog(self, "Choose a file:", style=wx.DD_DEFAULT_STYLE, defaultDir=cur_dirname, defaultFile=cur_basename, wildcard=self.allowed_extensions) # TODO: defaultFile is not being set to cur_basename in the dialog box else: dlg = wx.DirDialog(self, "Choose a directory:", style=wx.DD_DEFAULT_STYLE, defaultPath=cur_dirname) if dlg.ShowModal() == wx.ID_OK: self._on_load(dlg.GetPath()) dlg.Destroy()
def audio_btn_click(self, e): openFileDialog = wx.FileDialog(self, "Select caps folder", "", "", "MP3 files (*.mp3)|*.mp3", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) openFileDialog.SetMessage("Select an audio file from to use") if openFileDialog.ShowModal() == wx.ID_CANCEL: return 'none' audio_track = openFileDialog.GetPath() self.audio_box.SetValue(str(audio_track))
def select_caps_folder(self): openFileDialog = wx.FileDialog(self, "Select caps folder", "", "", "JPG files (*.jpg)|*.jpg", wx.FD_OPEN | wx.FD_FILE_MUST_EXIST) openFileDialog.SetMessage("Select an image from the caps folder you want to import") if openFileDialog.ShowModal() == wx.ID_CANCEL: return 'none' new_cap_path = openFileDialog.GetPath() capsdir = os.path.split(new_cap_path) capset = capsdir[1].split(".")[0][0:-10] # Used to select set if more than one are present cap_type = capsdir[1].split('.')[1] capsdir = capsdir[0] + '/' print(" Selected " + capsdir + " with capset; " + capset + " filetype; " + cap_type) return capsdir, capset, cap_type
def __init__(self, parent, name, objectpath, textwidth, file_extension): def assign(input): self.objectpath.ChangeValue(input) def OnBrowse(self): if IsNotWX4(): dlg = wx.FileDialog(parent, 'Choose a file', os.getcwd(), '', file_extension, wx.OPEN) else: dlg = wx.FileDialog(parent, 'Choose a file', os.getcwd(), '', file_extension, wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: assign(dlg.GetPath()) dlg.Destroy() def OnEdit(event): self.objectpath.ChangeValue(event.GetString()) fontpointsize=wx.SystemSettings.GetFont(wx.SYS_SYSTEM_FONT).GetPointSize() self.font = wx.Font(fontpointsize, wx.FONTFAMILY_SWISS, wx.FONTSTYLE_NORMAL, wx.FONTWEIGHT_NORMAL) dc = wx.ScreenDC() dc.SetFont(self.font) textw,texth = dc.GetTextExtent(name) if textw > textwidth: labelw = textw else: labelw = textwidth wx.BoxSizer.__init__(self, wx.HORIZONTAL) self.label = StaticTextNew(parent, -1, name, style =wx.ALIGN_RIGHT, size=(labelw,-1) ) self.label.SetFont(self.font) self.Add( self.label, 0, wx.CENTER ) self.objectpath = TextCtrlNew(parent, -1) self.objectpath.SetFont(self.font) self.objectpath.SetValue(objectpath) self.objectpath.SetToolTipNew("Browse for file or type "+os.linesep+"path and name") self.objectpath.Bind(wx.EVT_TEXT_ENTER, OnEdit) self.Add( self.objectpath, 1, wx.CENTER |wx.EXPAND ) self.button = ButtonNew(parent, -1, "Browse") self.button.SetFont(self.font) self.button.SetToolTipNew("Browse for file or type "+os.linesep+"path and name") self.button.Bind(wx.EVT_BUTTON, OnBrowse) self.Add( self.button, 0, wx.LEFT|wx.CENTER)
def OnOpen(self,e): panelphase = self.GetChildren()[1].GetPage(0) if panelphase.pipeline_started == False: cwd = self.CurrentWD() if IsNotWX4(): dlg = wx.FileDialog(self, "Choose a file", cwd, "", "fin files (*.fin)|*.fin|All files (*.*)|*.*", wx.OPEN) else: dlg = wx.FileDialog(self, "Choose a file", cwd, "", "fin files (*.fin)|*.fin|All files (*.*)|*.*", wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: self.filename = dlg.GetFilename() self.dirname = dlg.GetDirectory() RestoreInstance(self) dlg.Destroy()
def OnSave(self,e): panelphase = self.GetChildren()[1].GetPage(0) if panelphase.pipeline_started == False: cwd = self.CurrentWD() if IsNotWX4(): dlg = wx.FileDialog(self, "Choose a file", cwd, "", "fin files (*.fin)|*.fin|All files (*.*)|*.*", wx.SAVE | wx.OVERWRITE_PROMPT) else: dlg = wx.FileDialog(self, "Choose a file", cwd, "", "fin files (*.fin)|*.fin|All files (*.*)|*.*", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: self.filename=dlg.GetFilename() self.dirname=dlg.GetDirectory() SaveInstance(self) dlg.Destroy()
def OnFileOpen(self, event): """Opens a selected file.""" dlg = wx.FileDialog(self, 'Choose a file to add.', '', '', '*.*', wx.OPEN) if dlg.ShowModal() == wx.ID_OK: fullPath = dlg.GetPath() imageFile = dlg.GetFilename() # checkDICMHeader() self.show_file(imageFile, fullPath)
def OnSaveMesh(self, evt): dlg = wx.FileDialog(self, "Choose a file", ".", "", "*", wx.SAVE) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetFilename() dirname = dlg.GetDirectory() filepath = os.path.join(dirname, filename) self.glcanvas.mesh.saveFile(filepath, True) self.glcanvas.Refresh() dlg.Destroy() return
def OnSaveScreenshot(self, evt): dlg = wx.FileDialog(self, "Choose a file", ".", "", "*", wx.SAVE) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetFilename() dirname = dlg.GetDirectory() filepath = os.path.join(dirname, filename) saveImageGL(self.glcanvas, filepath) dlg.Destroy() return
def OnSaveMesh(self, evt): dlg = wx.FileDialog(self, "Choose a file", ".", "", "*", wx.FD_SAVE) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetFilename() dirname = dlg.GetDirectory() filepath = os.path.join(dirname, filename) self.glcanvas.mesh.saveFile(filepath, True) self.glcanvas.Refresh() dlg.Destroy() return
def on_open(self,e): """ Open a file""" self.dirname = '' dlg = wx.FileDialog(self, "Choose a deck", self.dirname, "", "*.db", wx.FD_OPEN) if dlg.ShowModal() == wx.ID_OK: self.filename = dlg.GetFilename() self.dirname = dlg.GetDirectory() print self.dirname, self.filename # f = open(os.path.join(self.dirname, self.filename), 'r') # self.control.SetValue(f.read()) # f.close() dlg.Destroy()
def browse(self, event): wildcard = "Audio and Video files ({wildcards})|{wildcards}".format(wildcards=';'.join(FILE_EXTS)) file_dialog = wx.FileDialog(self, message="Select files", style=wx.FD_OPEN | wx.FD_MULTIPLE | wx.FD_FILE_MUST_EXIST, wildcard=wildcard) file_dialog.SetDirectory(self.in_dir) if self.in_dir else None if file_dialog.ShowModal() != wx.ID_OK: file_dialog.Destroy() return self.in_files = file_dialog.GetPaths() self.in_picker.GetTextCtrl().SetValue(str(file_dialog.GetFilenames()).strip('[]')) file_dialog.Destroy()
def save_dialogue(self, event, defaultFile): dlg = wx.FileDialog(self, defaultDir='./', defaultFile=defaultFile, style=wx.FD_SAVE) if (dlg.ShowModal() == wx.ID_OK): fpath = dlg.GetPath() dlg.Destroy() #Check if defined, if cancel pressed then return try: fpath except NameError: return if defaultFile == 'fig.png': try: print('Saving figure as ' + fpath) self.pyplotp.savefigure(fpath) print('Saved.') except ValueError: raise elif defaultFile == 'data.csv': print('Writing data as ' + fpath) self.pyplotp.writedatacsv(fpath) print('Finished.') elif defaultFile == 'script.py': self.pyplotp.writescript(fpath) #Output error as dialogue #import sys #exc_info = sys.exc_info() #print(exc_info, dir(exc_info), type(exc_info)) #showMessageDlg(exc_info[1])
def OnOpenProjectMenu(self, event): if self.Controler is not None and not self.CheckSaveBeforeClosing(): return filepath = "" if self.Controler is not None: filepath = self.Controler.GetFilePath() if filepath != "": directory = os.path.dirname(filepath) else: directory = os.getcwd() result = None dialog = wx.FileDialog(self, _("Choose a file"), directory, "", _("PLCOpen files (*.xml)|*.xml|All files|*.*"), wx.OPEN) if dialog.ShowModal() == wx.ID_OK: filepath = dialog.GetPath() if os.path.isfile(filepath): self.ResetView() controler = PLCControler() result = controler.OpenXMLFile(filepath) self.Controler = controler self.LibraryPanel.SetController(controler) self.ProjectTree.Enable(True) self.PouInstanceVariablesPanel.SetController(controler) self._Refresh(PROJECTTREE, LIBRARYTREE) self._Refresh(TITLE, EDITORTOOLBAR, FILEMENU, EDITMENU) dialog.Destroy() if result is not None: (num, line) = result self.ShowErrorMessage(_("PLC syntax error at line {a1}:\n{a2}").format(a1=num, a2=line))