我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtWidgets.QFileDialog.getOpenFileName()。
def load_image(self): ''' ???? ''' try: im_path,_=QFileDialog.getOpenFileName(self,'??????','./','Image Files(*.png *.jpg *.bmp)') if not os.path.exists(im_path): return self.im_path=im_path self.statu_text.append('???????'+self.im_path) if not self.swapper: self.swapper=Coupleswapper([self.im_path]) elif not self.im_path== self.cur_im_path: self.swapper.load_heads([self.im_path]) self.img_ori=self.swapper.heads[os.path.split(self.im_path)[-1]][0] cv2.imshow('Origin',self.img_ori) except (TooManyFaces,NoFace): self.statu_text.append(traceback.format_exc()+'\n????????????????????????????') return
def choosePathButton(self): sender = self.sender() if sender.objectName() == "pushButton_mediainfo_path": lineEdit = self.findChild(QLineEdit, "lineEdit_mediainfo_path") exe_name = "mediainfo" elif sender.objectName() == "pushButton_mp3guessenc_path": lineEdit = self.findChild(QLineEdit, "lineEdit_mp3guessenc_path") exe_name = "mp3guessenc" elif sender.objectName() == "pushButton_sox_path": lineEdit = self.findChild(QLineEdit, "lineEdit_sox_path") exe_name = "sox" elif sender.objectName() == "pushButton_ffprobe_path": lineEdit = self.findChild(QLineEdit, "lineEdit_ffprobe_path") exe_name = "ffprobe" elif sender.objectName() == "pushButton_aucdtect_path": lineEdit = self.findChild(QLineEdit, "lineEdit_aucdtect_path") exe_name = "aucdtect" if lineEdit is not None: path = lineEdit.text() file = str(QFileDialog.getOpenFileName(parent=self, caption=self.tr("Browse to")+" {} ".format(exe_name)+self.tr("executable file"), directory=path)[0]) if not file == "": lineEdit.setText(file)
def _pick_firmware(self): firmware_dir = None if Settings().last_firmware_directory: firmware_dir = Settings().last_firmware_directory p = QFileDialog.getOpenFileName(parent=self, caption="Select python executable", directory=firmware_dir, filter="*.bin") path = p[0] if path: self.firmwarePathEdit.setText(path) Settings().last_firmware_directory = "/".join(path.split("/")[0:-1])
def open_sheet(self): self.check_change = False path = QFileDialog.getOpenFileName(self, 'Open CSV', os.getenv('HOME'), 'CSV(*.csv)') if path[0] != '': with open(path[0], newline='') as csv_file: self.setRowCount(0) self.setColumnCount(10) my_file = csv.reader(csv_file, delimiter=',', quotechar='|') for row_data in my_file: row = self.rowCount() self.insertRow(row) if len(row_data) > 10: self.setColumnCount(len(row_data)) for column, stuff in enumerate(row_data): item = QTableWidgetItem(stuff) self.setItem(row, column, item) self.check_change = True
def open_sheet(self): self.check_change = False path = QFileDialog.getOpenFileName(self, 'Open CSV', os.getenv('HOME'), 'CSV(*.csv)') if path[0] != '': with open(path[0], newline='') as csv_file: self.setRowCount(0) self.setColumnCount(10) my_file = csv.reader(csv_file, dialect='excel') for row_data in my_file: row = self.rowCount() self.insertRow(row) if len(row_data) > 10: self.setColumnCount(len(row_data)) for column, stuff in enumerate(row_data): item = QTableWidgetItem(stuff) self.setItem(row, column, item) self.check_change = True
def add_nodeset(self): path, ok = QFileDialog.getOpenFileName(self.view, caption="Import OPC UA XML Node Set", filter="XML Files (*.xml *.XML)", directory=".") if not ok: return None name = os.path.basename(path) if name in self.nodesets: return try: self.server_mgr.import_xml(path) except Exception as ex: self.error.emit(ex) raise item = QStandardItem(name) self.model.appendRow([item]) self.nodesets.append(name) self.view.expandAll() self.nodeset_added.emit(path)
def openFile(self): filePath, _ = QFileDialog.getOpenFileName(self, "Open File", self.xmlPath, "XML files (*.xml);;HTML files (*.html);;" "SVG files (*.svg);;User Interface files (*.ui)") if filePath: f = QFile(filePath) if f.open(QIODevice.ReadOnly): document = QDomDocument() if document.setContent(f): newModel = DomModel(document, self) self.view.setModel(newModel) self.model = newModel self.xmlPath = filePath f.close()
def get_file_content(self): filename = QFileDialog.getOpenFileName(None, 'Open file')[0] if filename is '': return '' try: with open(filename, 'r') as file: try: return str(file.read()) except Exception as e: QMessageBox.warning(None, 'Can not open file', 'Can not open file {}:\n{}'.format(filename, e)) return '' except IOError: return '' ## # \brief Returns the remaining rate limit # # Returns -1 if an error occurred. This request do not xount against the rate limit. # # \return Rate limit or -1 if error occurred
def getLogoFilePath(self, lblwidget): self.ui.lbl_browse.clear() filename, _ = QFileDialog.getOpenFileName( self, 'Open File', " ../../", 'Images (*.png *.svg*.jpg)', None, QFileDialog.DontUseNativeDialog) flag = True if filename == '': flag = False return flag else: base = os.path.basename(str(filename)) lblwidget.setText(base) self.desired_location(filename) return str(filename)
def importText(self, item): # get file path f_path, filters = QFileDialog.getOpenFileName( self, 'Select the text file that contains links') # if path is correct: if os.path.isfile(str(f_path)): # create a text_queue_window for getting information. text_queue_window = TextQueue( self, f_path, self.queueCallback, self.persepolis_setting) self.text_queue_window_list.append(text_queue_window) self.text_queue_window_list[len( self.text_queue_window_list) - 1].show() # callback of text_queue_window and plugin_queue_window.AboutWindowi # See importText and pluginQueue method for more information.
def importImageThread(self): self.statusbar = 'Importing Image...' self.image = QFileDialog.getOpenFileName(self, 'Choose Image', os.sep.join((os.path.expanduser('~'), 'Desktop')), 'Image Files (*.png *.jpg *.jpeg)') importThread = threading.Thread(target=self.importImage) importThread.start()
def openFileTrain(self): """ Opens a file dialog to select the file for training. Parameters ---------- None Return ---------- None """ self.path_train, _ = QFileDialog.getOpenFileName(self.train, "Select Database File", "", "All files (*.*)")
def openFileValidate(self): """ Opens a file dialog to select the file for validation. Parameters ---------- None Return ---------- None """ self.path_validate, _ = QFileDialog.getOpenFileName(self.validate, "Select Database File", "", "All files (*.*)")
def _pick_python(self): p = QFileDialog.getOpenFileName(parent=self, caption="Select python executable") path = p[0] if path: self.pythonPathEdit.setText(path) Settings().python_flash_executable = path
def on_load_batch_file_pressed(self): file = QFileDialog.getOpenFileName() with open(file[0]) as f: lines = f.read().splitlines() self.batch_load(lines)
def openFileNameDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options) if fileName: print(fileName)
def open_text(self): filename = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME')) with open(filename[0], 'r') as f: file_text = f.read() self.text.setText(file_text)
def openFileNameDialog(self): print("set icon clicked") options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self, "Choose Contact Icon", "", "Image Files (*.jpg *.png)", options=options) if fileName: print(fileName) pixmap = QtGui.QPixmap(fileName) self.contact_icon.setPixmap(pixmap) self.contact_icon.setScaledContents(True) # pixmap2 = self.contact_icon.pixmap() # print(pixmap2)
def OpenFileDialog(self, title): self.filename, _ = getOpenFileName(self, title, g.config.vars.Paths['import_dir'], self.tr("All supported files (*.dxf *.ps *.pdf *%s);;" "DXF files (*.dxf);;" "PS files (*.ps);;" "PDF files (*.pdf);;" "Project files (*%s);;" "All types (*.*)") % (c.PROJECT_EXTENSION, c.PROJECT_EXTENSION)) # If there is something to load then call the load function callback if self.filename: self.filename = file_str(self.filename) logger.info(self.tr("File: %s selected") % self.filename)
def load_probe_data_dialog(self): fname, mask = QFileDialog.getOpenFileName(None, "Load probe data", "", "Log data (*.txt *.log);;All files (*.*)") if fname: self.load_probe_data(fname)
def fileOpenDLMNIST(self): """ Open and load DLM File """ # Get data and load into CRI_HSI class # This will need to change to accomodate multiple-file selection filename_header,_ = _QFileDialog.getOpenFileName(self, 'Open Header File', './', 'All Files (*.*)') if filename_header != '': self.path = _os.path.dirname(filename_header) + '/' filename_data,_ = _QFileDialog.getOpenFileName(self, 'Open Data File', self.path, 'All Files (*.*)') if filename_data != '': self.path = _os.path.dirname(filename_data) + '/' self.filename = filename_data.split(_os.path.dirname(filename_data))[1][1::] self.filename_header = filename_header success = io_nist_dlm(self.path, self.filename_header, self.filename, self.hsi) self.fileOpenSuccess(success)
def loadDarkDLM(self): """ Open DLM file and load dark spectrum(a) """ filename,_ = _QFileDialog.getOpenFileName(self, 'Open Dark File', self.path, 'All Files (*.*)') if filename != '': filename = filename.split(_os.path.dirname(filename))[1][1::] # Spectra first self.dark = Spectra() success = io_nist_dlm(self.path, self.filename_header, filename, self.dark) if not success: # Maybe Spectrum self.dark = Spectrum() success = io_nist_dlm(self.path, self.filename_header, filename, self.dark) # print('Success: {}'.format(success)) if success: if self.dark.shape[-1] == self.hsi.freq.size: self.ui.actionDarkSubtract.setEnabled(True) self.ui.actionDarkSpectrum.setEnabled(True) else: self.dark = Spectra() print('Dark was the wrong shape') else: self.dark = Spectra() self.ui.actionDarkSubtract.setEnabled(False) self.ui.actionDarkSpectrum.setEnabled(False)
def loadNRBDLM(self): """ Open DLM file and load NRB spectrum(a) """ filename, _ = _QFileDialog.getOpenFileName(self, 'Open NRB File', self.path, 'All Files (*.*)') if filename != '': filename = filename.split(_os.path.dirname(filename))[1][1::] # Spectra first self.nrb = Spectra() success = io_nist_dlm(self.path, self.filename_header, filename, self.nrb) if not success: # Maybe Spectrum self.nrb = Spectrum() success = io_nist_dlm(self.path, self.filename_header, filename, self.nrb) print('Success: {}'.format(success)) if success: if self.dark.shape[-1] == self.hsi.freq.size: self.ui.actionKramersKronig.setEnabled(True) self.ui.actionKKSpeedTest.setEnabled(True) self.ui.actionNRBSpectrum.setEnabled(True) self.ui.actionDeNoiseNRB.setEnabled(True) else: self.nrb = Spectra() print('NRB was the wrong shape') else: self.nrb = Spectra() self.ui.actionKramersKronig.setEnabled(False) self.ui.actionKKSpeedTest.setEnabled(False) self.ui.actionNRBSpectrum.setEnabled(False) self.ui.actionDeNoiseNRB.setEnabled(False)
def getFilenameFromUserSelection(file_types="Any Files (*.*)", path = ''): filenames, _ = QFileDialog.getOpenFileName(None, "??????? ????", path, file_types, None) if (len(filenames) > 0): return filenames else: return None
def get_open_file_name(caption='', filter_text=''): result = QFileDialog.getOpenFileName(None, caption, get_default_dir(), filter_text)[0] if result: set_default_dir(os.path.dirname(os.path.abspath(result))) return result
def open(self): if not self.try_close_model(): return path, ok = QFileDialog.getOpenFileName(self.modeler, caption="Open OPC UA XML", filter="XML Files (*.xml *.XML)", directory=self._last_model_dir) if not ok: return if self._last_model_dir != os.path.dirname(path): self._last_model_dir = os.path.dirname(path) self.settings.setValue("last_model_dir", self._last_model_dir) self._model_mgr.open_model(path)
def import_xml(self): last_import_dir = self.settings.value("last_import_dir", ".") path, ok = QFileDialog.getOpenFileName(self.modeler, caption="Import reference OPC UA XML", filter="XML Files (*.xml *.XML)", directory=last_import_dir) if not ok: return None self.settings.setValue("last_import_dir", last_import_dir) self._model_mgr.import_xml(path)
def cb_file_browse_push_button(self): # get file name file_name = QFileDialog.getOpenFileName(self._app.windows['backgroundWindow'], 'Select File', '') file_name = file_name[0] # check if a file has been selected if file_name == '': return # set file name to line edit self.ui.file_path_line_edit.setText(file_name)
def cfm_get_obs_file(self): fl, _ = QFileDialog.getOpenFileName(self, "Select Observed File", filter="CSV files (*.csv)") self.ui.observedFileEdit.setText(fl)
def cfm_get_his_file(self): fl, _ = QFileDialog.getOpenFileName(self, "Select Historical GCM File", filter="CSV files (*.csv)") self.ui.historicalFileEdit.setText(fl)
def cfm_get_fut_file(self): fl, _ = QFileDialog.getOpenFileName(self, "Select Future GCM File", filter="CSV files (*.csv)") self.ui.futureFileEdit.setText(fl)
def knn_get_input_file(self): fl, _ = QFileDialog.getOpenFileName(self, "Select Input File", filter="CSV files (*.csv)") self.ui.knnInputEdit.setText(fl)
def on_action_import_parameter_values_triggered(self): with self.catcher.more: filename, _ = QFileDialog.getOpenFileName( parent=self, caption='Import Parameter Values', directory='.', filter='Supported Files (*.sunsynth *.sunvox)', ) if filename: obj = rv.read_sunvox_file(filename) if isinstance(obj, rv.Project): project = obj elif isinstance(obj, rv.Synth) and isinstance(obj.module, rv.m.MetaModule): project = obj.module.project else: print('{} is not a project or metamodule'.format(filename)) return mmckdata = None for mod in reversed(project.modules): if mod.name == 'mmckdata': mmckdata = mod break if not mmckdata: print('Could not find mmckdata module in {}'.format(filename)) return params = json.loads(mmckdata.samples[-2].data.decode('utf8')) self.kit.parameter_values.update(params) self.parameters_manager.parameters = self.kit.parameters self.rebuild_project() self.save_kit_parameter_values() if hasattr(self.kit.py_module, 'udc_assignments'): self.update_udc_assignments(self.kit.py_module.udc_assignments(self.kit.parameter_values)) print('Imported parameter values from {}'.format(filename))
def requested_filename(self, directory='.'): return QFileDialog.getOpenFileName( parent=self.parent, caption=self.caption, directory=directory, filter=self.filter(), )
def getOpenFileName(parent=None, dir=None, filter=None, caption=None): if (dir == None): dir = QDir.currentPath() if (filter == None): filter = 'File (*.*)' filename = QFileDialog.getOpenFileName(parent, caption, dir, filter) if (filename == ('', '')): # two null strings for cancel return None return filename[0]
def Open(self): filename = QFileDialog.getOpenFileName(self, 'Open File') f = open(filename, 'r') filedata = f.read() self.text.getTextEdit().setText(filedata) f.close()
def openFileNameDialog(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName(self,"QFileDialog.getOpenFileName()", "","All Files (*);;Python Files (*.py)", options=options) if fileName: return str(fileName) else: return 'Path to the file used to start miner'
def on_btn_choose_file_clicked(self): filename, _ = QFileDialog.getOpenFileName(self, self.tr("Choose file"), directory=FileOperator.RECENT_PATH, filter="CSV files (*.csv);;All files (*.*)") if filename: self.ui.lineEditFilename.setText(filename) self.ui.lineEditFilename.editingFinished.emit()
def get_file_path(self, title): return QFileDialog.getOpenFileName(None, title)[0] ## # \brief Qt slot for check_user_and_secret(). # # Tests if user/secret file is setup correctly and shows error message if not.
def new_process_dialog(self): """ Open the File dialog used to select a B3 configuration file. """ self.make_visible() init = b3.getAbsolutePath('@b3/conf') extensions = ['INI (*.ini)', 'XML (*.xml)', 'All Files (*.*)'] path, _ = QFileDialog.getOpenFileName(self.centralWidget(), 'Select configuration file', init, ';;'.join(extensions)) self.make_new_process(path)
def install_plugin(self): """ Handle the install of a new B3 plugin. """ self.make_visible() init = b3.getAbsolutePath('~') path, _ = QFileDialog.getOpenFileName(self.centralWidget(), 'Select plugin package', init, 'ZIP (*.zip)') if path: install = PluginInstallDialog(self.centralWidget(), path) install.show()
def but_select_orig_clicked(self): self.text_path_orig.setText(QFileDialog.getOpenFileName()[0])
def _old_epub_dialog(self): self.old_epub = QFileDialog.getOpenFileName(self, self.tr("Open EPUB"), "", "EPUB (*.epub)")[0] if self.old_epub: self.old_epub_button.setText(os.path.basename(self.old_epub)) else: self.old_epub_button.setText(self.tr("Select File...")) self.completeChanged.emit()
def _new_epub_dialog(self): self.new_epub = QFileDialog.getOpenFileName(self, self.tr("Open EPUB"), "", "EPUB (*.epub)")[0] if self.new_epub: self.new_epub_button.setText(os.path.basename(self.new_epub)) else: self.new_epub_button.setText(self.tr("Select File...")) self.completeChanged.emit()