def askUserToBreakTie(self, candidates, names, what): "Provide a window to ask the user to break a tie." instructions = """\ Tie when selecting %s. Break the tie by selecting a candidate or choose Cancel to break the tie randomly.""" % what dlg = wx.SingleChoiceDialog(self.frame, instructions, "Break Tie Manually", names, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: selection = dlg.GetStringSelection() i = names.index(selection) return candidates[i] else: return None
def OnLeftLink(self, event): listeLabels = [] for code, label in self.parent.listeChamps: listeLabels.append(u"%s (%s)" % (label, code)) dlg = wx.SingleChoiceDialog(None, _(u"Sélectionnez un champ à insérer :"), _(u"Insérer un champ"), listeLabels, wx.CHOICEDLG_STYLE) dlg.SetSize((580, 700)) dlg.CenterOnScreen() if dlg.ShowModal() == wx.ID_OK: champ = self.parent.listeChamps[dlg.GetSelection()][0] self.parent.InsertTexte(u"{%s}" % champ) dlg.Destroy() self.UpdateLink()
def __OnPresetRemove(self, event): presetsList = list() presetsDict = dict() for preset in self.sim.savedPresets.configPresets: presetsList.append(preset.name) presetsDict[preset.name] = preset dlg = wx.SingleChoiceDialog(self, "Choose a preset to remove.", "Preset List", presetsList, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: self.sim.savedPresets.configPresets.remove( presetsDict[dlg.GetStringSelection()]) dlg.Destroy() self.RebuildMenus()
def task_set_status(parent, task): """Reset the status of the task.""" choices = [str(s) for s in flowtk.Node.ALL_STATUS] dialog = wx.SingleChoiceDialog(parent, message="Select new status", caption="", choices=choices) if dialog.ShowModal() == wx.ID_CANCEL: return None status = choices[dialog.GetSelection()] dialog.Destroy() task.set_status(status, info_msg="Status changed by user on %s" % time.asctime()) #task.reset() check_status_and_pickle(task)
def GetSelectedAxis(self, selectionable, title="", text=""): """ Returns the index of the axis selected. -selectionable: List of selectionable axes. -title: Title of the dialog. -text: Text of the dialog. """ axis = -1 dlg = wx.SingleChoiceDialog(self, title, text, selectionable) if dlg.ShowModal() == wx.ID_OK: axisName = dlg.GetStringSelection() # Get the index for i in range(len(self.labels)): if self.labels[i] == axisName: axis = i return axis
def handler_audio(sel_res): audio_info = sel_res.getAllAudioInfo() if audio_info: dlg = wx.SingleChoiceDialog(gui.frame_parse, u'Pick the AUDIO you prefer', u'Audio Choice', audio_info) if dlg.ShowModal() == wx.ID_OK: index = audio_info.index(dlg.GetStringSelection()) sel_res.setSelAudio(index) dlg.Destroy() else: dlg.Destroy() return False return True
def Choose( title = '' , prompt = '' , OptionList = [] , response = None ): dialog = wx.SingleChoiceDialog( None, title , prompt , OptionList ) # prepare the dialog if not OptionList == []: # ensure the list is not empty if dialog.ShowModal() == wx.ID_OK: # check the dialog response return dialog.GetStringSelection() # return the selected string else: return None dialog.Destroy() # destroy the dialog else: return None
def choosePrinter(filename): conn = cups.Connection() p = conn.getPrinters() pList = [] for printer in p: pList.append(printer) printerDialog = wx.SingleChoiceDialog(None, "Choose a printer.", "Printers", pList, style=wx.OK | wx.CANCEL) if printerDialog.ShowModal() == wx.ID_OK: os.system("lp -d %s %s" % (printerDialog.GetStringSelection(), filename)) #extremely slick: prints directly to printer
def OnCODQuery(self, event): db = pymysql.connect('sql.crystallography.net', 'cod_reader', None, 'cod') c = db.cursor() formula = [] for element, number in self.extracted_elements: if element.startswith('^'): element = element.split('}')[-1] if number != 1: formula.append('%s%g' % (element, number)) else: formula.append('%s' % element) formula = ' '.join(sorted(formula)) c.execute('select a,b,c,alpha,beta,gamma,' 'Z,vol,sg,chemname,mineral,commonname,' 'authors,title,journal,year' ' from data where formula like "- %s -"' ' and status is NULL order by file' % formula) res = c.fetchall() if len(res) > 0: # more then one structure available, ask for user input to select appropriate items = [] for i, ri in enumerate(res): a, b, c = ri[:3] Z = ri[6] or 1. V = ri[7] or a * b * c sgs = ri[8] dens = self.extracted_elements.mFU( ) * Z / V / MASS_DENSITY_CONVERSION name = ri[10] or ri[11] or ri[9] or "" text = '%s\n%s\n%s (%s)' % tuple(ri[12:16]) items.append( '%i: %s (%s) | Density: %.3g g/cm³ | UC Volume: %s\n%s' % (i + 1, name, sgs, dens, V, text)) dia = wx.SingleChoiceDialog( self, 'Several entries have been found, please select appropriate:', 'Select correct database entry', items) if not dia.ShowModal() == wx.ID_OK: return None res = res[dia.GetSelection()] else: return None for value, entry in zip(res, [ self.a_entry, self.b_entry, self.c_entry, self.alpha_entry, self.beta_entry, self.gamma_entry, self.FUs_entry ]): entry.SetValue(str(value or ""))
def GetProjectForDoc(doc): """ Given a document find which project it belongs to. Tries to intelligently resolve conflicts if it is in more than one open project. """ projectService = wx.GetApp().GetService( project.ProjectEditor.ProjectService) projectDoc = projectService.FindProjectFromMapping(doc) if projectDoc: return projectDoc projectDoc = projectService.GetCurrentProject() if not projectDoc: return None if projectDoc.IsFileInProject(doc.GetFilename()): return projectDoc projects = [] openDocs = wx.GetApp().GetDocumentManager().GetDocuments() for openDoc in openDocs: if openDoc == projectDoc: continue if (isinstance(openDoc, project.ProjectEditor.ProjectDocument)): if openDoc.IsFileInProject(doc.GetFilename()): projects.append(openDoc) if projects: if len(projects) == 1: return projects[0] else: choices = [ os.path.basename(project.GetFilename()) for project in projects ] dlg = wx.SingleChoiceDialog( wx.GetApp().GetTopWindow(), _("'%s' found in more than one project.\nWhich project should be used for this operation?" ) % os.path.basename(doc.GetFilename()), _("Select Project"), choices, wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER | wx.OK | wx.CENTRE) dlg.CenterOnParent() projectDoc = None if dlg.ShowModal() == wx.ID_OK: i = dlg.GetSelection() projectDoc = projects[i] dlg.Destroy() return projectDoc return None
def process_adv_argv(): global _PARAM if not ("args" in _PARAM and len(_PARAM["args"]) > 0): _app = wx.App() choices = [ ff for ff in os.listdir(PATHS["PRJ_PATH"]) if not ff.startswith("_") and os.path.isdir(os.path.join(PATHS["PRJ_PATH"], ff)) ] dlg = wx.SingleChoiceDialog( None, _("select the application to run"), _("Pytigon"), choices, wx.CHOICEDLG_STYLE, ) if dlg.ShowModal() == wx.ID_OK: arg = dlg.GetStringSelection() dlg.Destroy() else: dlg.Destroy() sys.exit(0) _app.MainLoop() _app = None else: arg = _PARAM["args"][0].strip() if not (arg == "embeded" or "." in arg or "/" in arg): CWD_PATH = os.path.join(PATHS["PRJ_PATH"], arg) if not os.path.exists(os.path.join(CWD_PATH, "settings_app.py")): print(_("Application pack: '%s' does not exists") % arg) sys.exit(0) else: sys.path.insert(0, CWD_PATH) try: from apps import GUI_COMMAND_LINE x = GUI_COMMAND_LINE.split(" ") param = process_argv(x) for key, value in param.items(): if not key in _PARAM: _PARAM[key] = value except: pass
def OnLeftLink(self, event): listeLabels = [] for track in self.parent.listeTracks: listeLabels.append( u"unite%d = %s (%s)" % (track.IDunite, track.nomUnite, track.nomActivite)) dlg = wx.SingleChoiceDialog( None, _(u"Sélectionnez une unité de consommation à insérer :"), _(u"Insérer une unité"), listeLabels, wx.CHOICEDLG_STYLE) dlg.SetSize((580, 450)) dlg.CenterOnScreen() if dlg.ShowModal() == wx.ID_OK: track = self.parent.listeTracks[dlg.GetSelection()] self.InsertTexte("unite%d" % track.IDunite) dlg.Destroy() self.hyper_formule.UpdateLink()
def onShowMembers(self, event): item = event.GetItem() layerMembers = list() layerName = item.GetText() key = item.GetData() layerData = self.layersDataDict[key] for i in range(len(layerData)): obj = self.editor.objectMgr.findObjectById(layerData[i]) namestr = "%s_%s" % (obj[OG.OBJ_DEF].name, obj[OG.OBJ_UID]) layerMembers.append(namestr) dialog = wx.SingleChoiceDialog(None, layerName, self.editorTxt, layerMembers) if dialog.ShowModal() == wx.ID_OK: #do something here dialog.GetStringSelection() dialog.Destroy()
def onPick(self, event): dlg = wx.SingleChoiceDialog(self, event.caption, 'Choose One', event.choices) try: index = event.choices.index(event.default) dlg.SetSelection(index) except ValueError: # selection not in list, ignore pass returnCode = dlg.ShowModal() dlg.Destroy() if returnCode == wx.ID_CANCEL: return None selection = event.choices[dlg.GetSelection()] self.parent.set_answer(selection) return selection
def get_action_list(self, file_list): if not file_list: file_list = self.get_action_list_files() d = {} for f in file_list: d[system.filename_to_title(f)] = f actionlists = d.keys() actionlists.sort() dlg = wx.SingleChoiceDialog(None, _('Select action list'), ct.TITLE, actionlists, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: actionlist = d[dlg.GetStringSelection()] else: actionlist = None dlg.Destroy() return actionlist
def SelectVideo(self, videofiles, selected_file=None): if len(videofiles) > 1: videofiles.sort() dialog = wx.SingleChoiceDialog( None, 'Tribler currently only supports playing one file at a time.\nSelect the file you want to play.', 'Which file do you want to play?', videofiles) if selected_file in videofiles: dialog.SetSelection(videofiles.index(selected_file)) selected_file = dialog.GetStringSelection() if dialog.ShowModal( ) == wx.ID_OK else None dialog.Destroy() return selected_file elif len(videofiles) == 1: return videofiles[0]
def HostSelection(self): items = [] resultHost = None for host in self.hosts: items.append("%s | %s" % (host['name'], host['addr'])) dlg = wx.SingleChoiceDialog( self, wordwrap(tr("select_player"), 300, wx.ClientDC(self)), tr("rasp_players"), items) result = dlg.ShowModal() selection = dlg.GetSelection() # print "RESULT: ", result if result == wx.ID_OK: resultHost = self.hosts[selection] # print "SELECTED HOST: ", resultHost return resultHost
def f2(artists): """Make a dialog with the artist names.""" if len(artists) == 1: artist = artists[0] else: dlg = wx.SingleChoiceDialog(application.frame, 'Select an artist', 'Multiple Artists', [x.name for x in artists]) if dlg.ShowModal() == wx.ID_OK: artist = artists[dlg.GetSelection()] else: artist = None dlg.Destroy() if artist is not None: Thread(target=callback, args=[artist, *args], kwargs=kwargs).start()
def printSDFile(self): self._sendCommand("M20") # setting = profile.settingsDictionary["printer_file_list"] # filelist = setting.getType() dlg = wx.SingleChoiceDialog(self, _("Please select file to print"),_( "Print SD File"), self.sdFiles) # dlg = wx.SingleChoiceDialog(self, "Please select file to print", "Print SD File", filelist) if dlg.ShowModal() == wx.ID_OK: filename = dlg.GetStringSelection() if len(filename) < 1: return askdlg = wx.MessageDialog(self, _("Do you want to print %s?") % filename, _("Tips"), wx.YES_NO) if askdlg.ShowModal() == wx.ID_YES: self._sendCommand(["M23 " + filename]) self._sendCommand("M24") askdlg.Destroy() dlg.Destroy()
def editAliases(self, event=None): """Edit aliases in a GUI.""" dlg = wx.SingleChoiceDialog( None, 'Edit aliases', 'Choose an alias to edit', [a.title for a in self.world.aliases.itervalues()]) res = dlg.ShowModal() if res == wx.ID_OK: alias = self.world.aliases.values()[dlg.GetSelection()] editor.AliasFrame(alias=alias.pattern.pattern, code=getattr(alias, '_code'), classes=alias.classes, title=alias.title, simple=alias.simple, add=self.world.addAlias, remove=self.world.removeAlias).Show(True) dlg.Destroy()
def SelectConfig(self, parent=None, force=False, new=False): ''' Shows dialog (if needed) to select configuration. ''' lst, choices = self.GetConfigList(new=new) if len(choices) == 1 and not force: return lst[0]['Id'] dlg = wx.SingleChoiceDialog( parent, _('Select which configration you want to modify.'), _('Select configuration section'), choices) if dlg.ShowModal() == wx.ID_OK: return lst[dlg.GetSelection()]['Id'] else: return None
def choice_entry( self, message: str, caption: str, choices: typing.List[str], default: typing.Optional[str] = None) -> typing.Optional[str]: with wx.SingleChoiceDialog(self, message, caption, choices=choices) as choice_dialog: if default is not None: try: choice_dialog.SetSelection(choices.index(default)) except ValueError: pass if choice_dialog.ShowModal() == wx.ID_CANCEL: return return choice_dialog.GetStringSelection()
def _select_option(self, title, label, columns, data, return_column): import wx # TODO: The column labels are not displayed and columns may not be aligned properly, # but is this really necessary for the puropse where it is used (encryption key # selection in 'pytis.remote.PytisService')? Maybe the definition of # 'select_option()' should be simplified. dialog = wx.SingleChoiceDialog(None, message=label, caption=title, choices=['\t'.join(item) for item in data]) if not dialog.HasFlag(wx.STAY_ON_TOP): dialog.ToggleWindowStyle(wx.STAY_ON_TOP) if dialog.ShowModal() != wx.ID_OK: result = None else: result = data[dialog.GetSelection()][return_column - 1] dialog.Destroy() return result
def chooseOpenApp(self, model, msg, capt): openApps = self.editor.getAppModules() if not openApps: wx.MessageBox(_('No open applications.'), style=wx.ICON_ERROR) return chooseApps = {} for app in openApps: chooseApps[os.path.basename(app.filename)] = app dlg = wx.SingleChoiceDialog(self.editor, msg, capt, chooseApps.keys()) try: if dlg.ShowModal() == wx.ID_OK: return chooseApps[dlg.GetStringSelection()] else: return None finally: dlg.Destroy()
def OnBtnCancelButton(self, event): global readThread global writeThread dlg = wx.SingleChoiceDialog( self, 'Are you sure you want to cancel the scanning job?', 'Confirmation', ['Yes', 'No']) try: if dlg.ShowModal() == wx.ID_OK: selected = dlg.GetStringSelection() # Your code if selected == 'Yes': readThread.Stop() writeThread.Stop() self.Close() finally: dlg.Destroy()
def OnImport(self, evt): with guihelper.WXDialogWrapper( wx.ProgressDialog( self._progress_dlg_title, 'Importing Outlook Data, please wait ...\n(Please also watch out for the Outlook Permission Request dialog)', parent=self)) as dlg: self._oc.read(None, dlg) self.populate(self._oc.get_display_data()) if self._oc.has_errors(): # display the list of failed items with guihelper.WXDialogWrapper( wx.SingleChoiceDialog(self, self._error_dlg_text, self._error_dlg_title, self._oc.get_error_list()), True): pass
def OnOpenDBFFile(self, event): if not self.shapefiles or len(self.shapefiles) < 1: return dbf_list = [shp.name for shp in self.shapefiles] dlg = wx.SingleChoiceDialog(self, 'Select a dbf file:', 'DBF table view', dbf_list, wx.CHOICEDLG_STYLE) if dlg.ShowModal() == wx.ID_OK: idx = dlg.GetSelection() #dbf = self.shapefiles[idx].dbf shapeFileObject = self.shapefiles[idx] name = shapeFileObject.name #dbf_widget = DataWidget(self,dbf,name) dbf_widget = DataWidget(self, shapeFileObject, name) dbf_widget.Show() dlg.Destroy()
def newItem(self, evt=None): msg = _translate("Add {}...").format(self.itemAlias) if self.options is None: _dlg = wx.TextEntryDialog(self.parent, message=msg) else: _dlg = wx.SingleChoiceDialog(self.parent, msg, "Input Text", choices=self.options) if _dlg.ShowModal() != wx.ID_OK: return if self.options is None: self.addItem(_dlg.GetValue()) else: self.addItem(_dlg.GetStringSelection())
def OnDone(self, evt): """ Select one config to use. """ if len(self.results) == 0: self.edit.AppendText(_('No phone has been found!') + '\n') return if len(self.results) > 1: # Allow user to select phone # FIXME: Might be in wizard, but this should be rare... choices = [] for phone in self.results: choices.append( _('Phone %(manufacturer)s %(model)s on device %(port)s using connection %(connection)s' ) % { 'model': phone[2][0], 'manufacturer': phone[3], 'port': phone[0], 'connection': phone[1] }) dlg = wx.SingleChoiceDialog( self, _('Select phone to use from below list'), _('Select phone'), choices) if dlg.ShowModal() == wx.ID_OK: idx = dlg.GetSelection() config = self.results[idx] else: self.results = [] config = None else: # Use directly only found phone config = self.results[0] if config is not None: self.parent.settings.SetPort(config[0]) self.parent.settings.SetGammuDriver(config[1]) self.edit.AppendText(_('Following phone will be used:') + '\n') self.edit.AppendText( _('Phone %(manufacturer)s %(model)s on device %(port)s using connection %(connection)s' ) % { 'model': config[2][0], 'manufacturer': config[3], 'port': config[0], 'connection': config[1] }) else: self.edit.AppendText(_('No phone selected!') + '\n')
def OnChoiceSelected(self, evt): """Handle EVT_CHOICE""" obj, e_id = evt.GetEventObject(), evt.GetId() sc = self.currentSystem if e_id == self.ID_SC_CHOICE: self.populateSystemOptions() elif e_id == self.ID_SC_REP_CHOICE: # Empty selection if not obj.GetStringSelection().strip(): obj.SetSelection(0) # Remove repository elif obj.GetSelection() == (obj.GetCount() - 1): # Default - Blank - Add - Remove: if only 4, there's nothing to remove if obj.GetCount() == 4: obj.SetSelection(0) else: choices = sorted([x for x in self._data.getSCRepositories(sc).keys() if x != 'Default']) scd = wx.SingleChoiceDialog(self, _('Select the repository path to remove'), _('Remove repository'), choices, style=wx.DEFAULT_DIALOG_STYLE|wx.OK|wx.CANCEL|wx.CENTER) if scd.ShowModal() == wx.ID_OK: value = scd.GetStringSelection().strip() self._data.removeSCRepository(sc, value) self.populateRepositoryList() # Add repository elif obj.GetSelection() == (obj.GetCount() - 2): ted = wx.TextEntryDialog(self, _('Please enter a repository path. Partial paths may also be entered.'), _('Add a New Repository Path'), style=wx.OK|wx.CANCEL|wx.CENTER) ted.SetSize((300, -1)) if ted.ShowModal() == wx.ID_OK: value = ted.GetValue().strip() if value: try: self._data.getSCRepository(self.currentSystem, value) except KeyError: self._data.addSCRepository(self.currentSystem, value) self.populateRepositoryList() obj.SetStringSelection(value) else: obj.SetSelection(0) else: obj.SetSelection(0) self.populateUserInfo() self.populateEnvironment() else: evt.Skip()