def __init__(self, parent, config): wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) scrolled_panel = ScrolledPanel(self) scrolled_panel.SetAutoLayout(1) scrolled_panel.SetupScrolling() main_sizer = wx.BoxSizer(wx.HORIZONTAL) grid_sizer = wx.FlexGridSizer(2, 10, 10) for index, entry in enumerate(config): if index > 0: for _ in range(0, 2): rule = wx.StaticLine( scrolled_panel, style=wx.LI_HORIZONTAL, size=(-1, 2) ) grid_sizer.Add(rule, proportion=1, flag=wx.EXPAND | wx.TOP | wx.BOTTOM, border=10) if entry.help_value: grid_sizer.Add(1, 0, 1, wx.EXPAND) help_sizer = wx.BoxSizer(wx.HORIZONTAL) help_label = HidableAutoWrapStaticText( parent=scrolled_panel, label=u"%s" % entry.help_value.decode('utf8', 'ignore'), kind='help_value', ) help_sizer.Add(help_label, -1, wx.EXPAND) grid_sizer.Add(help_sizer, 1, wx.EXPAND) label_sizer = wx.BoxSizer(wx.VERTICAL) label_sizer.Add(0, 1, 1, wx.EXPAND) label = wx.StaticText( scrolled_panel, label=entry.key_name, style=wx.ALIGN_RIGHT ) label_sizer.Add(label, flag=wx.ALIGN_RIGHT) label_sizer.Add(0, 1, 1, wx.EXPAND) grid_sizer.Add(label_sizer, 0, wx.EXPAND) current_value = wx.TextCtrl( scrolled_panel, value=str(entry.current), size=(-1, -1) ) grid_sizer.Add(current_value, -1, wx.EXPAND) if entry.man: grid_sizer.Add(1, 0, 1, wx.EXPAND) man_sizer = wx.BoxSizer(wx.HORIZONTAL) man_label = HidableAutoWrapStaticText( parent=scrolled_panel, label=u"%s" % entry.man.decode('utf8', 'ignore'), kind='man', ) man_sizer.Add(man_label, -1, wx.EXPAND) grid_sizer.Add(man_sizer, 1, wx.EXPAND) grid_sizer.AddGrowableCol(1, 1) scroll_sizer = wx.BoxSizer(wx.HORIZONTAL) scroll_sizer.Add(grid_sizer, 1, wx.EXPAND | wx.ALL, 10) scrolled_panel.SetSizer(scroll_sizer) main_sizer.Add(scrolled_panel, 1, wx.EXPAND) self.SetSizer(main_sizer)
def update(self, **kwargs): """ Results ------- wxPanel obj https://stackoverflow.com/questions/3104323/getting-a-wxpython-panel-item-to-expand """ p1 = ScrolledPanel(self, -1, style=wx.TAB_TRAVERSAL | wx.SUNKEN_BORDER, name="panel1") p1.SetBackgroundColour("White") vbox = wx.BoxSizer(wx.VERTICAL) txt_info = wx.StaticText(p1, -1, txt) txt_info.SetForegroundColour("Green") vbox.Add(txt_info, 0, wx.ALIGN_LEFT | wx.ALL, 5) vbox.Add(wx.StaticLine(p1, -1, size=(1024, -1)), 0, wx.ALL, 5) vbox.Add((20, 20)) p1.SetSizer(vbox) p1.SetAutoLayout(1) p1.SetupScrolling() return p1
def _create_control(self, parent): """ Create the toolkit-specific control that represents the widget. """ panel = ScrolledPanel(parent, -1, style=self.STYLE) sizer = wx.BoxSizer(wx.VERTICAL) panel.SetSizer(sizer) panel.SetAutoLayout(True) panel.SetupScrolling() return panel
def __init__(self, parent): wx.Dialog.__init__(self, parent, id=wx.ID_ANY, title=u"车辆保险到期提醒", pos=wx.DefaultPosition, size=(800, 530), style=wx.CAPTION | wx.STAY_ON_TOP | wx.RESIZE_BORDER) self.alarm_time = None border = wx.BoxSizer(wx.VERTICAL) # 操作条 opt_sizer = wx.BoxSizer(wx.HORIZONTAL) if not auth.Auth.logon_user[2] == 2: export_btn = wx.Button(self, wx.ID_ANY, u"导出") self.Bind(wx.EVT_BUTTON, self.on_export, export_btn) opt_sizer.Add(export_btn, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) border.Add(opt_sizer, 0, wx.ALIGN_RIGHT, 5) # 网格条 grid_boxer = wx.BoxSizer(wx.HORIZONTAL) panel = ScrolledPanel(self, size=(780, 400)) alarm_grid = vehiclepanel.VehicleGrid(panel) # 加载预警数据 self.data = service.search_vehicle(30, None) alarm_grid.set_data(self.data) grid_boxer.Add(alarm_grid, 0, wx.ALIGN_TOP, 5) panel.SetSizer(grid_boxer) panel.Fit() panel.SetAutoLayout(1) panel.SetupScrolling() border.Add(panel, 0, wx.FIXED_MINSIZE, 5) # 按钮条 buttons = wx.BoxSizer() self.close_btn = wx.Button(self, wx.ID_OK, u"关闭") self.close_btn.SetDefault() self.close_btn.Enable(False) buttons.Add(self.close_btn) border.Add(buttons, 0, wx.ALIGN_RIGHT | wx.ALL, 5) self.SetSizer(border)
def main(): from wx.lib.scrolledpanel import ScrolledPanel app = wx.PySimpleApp() frame = wx.Frame(None, wx.ID_ANY, __doc__) #~ sizer = wx.GridSizer(1, 1) #~ canvas = irrlicht_canvas(frame) panel = ScrolledPanel(frame, wx.ID_ANY) sizer = wx.GridSizer(1, 1) canvas = irrlicht_canvas(panel) sizer.Add(canvas, 0, wx.EXPAND | wx.ALL) panel.SetSizer(sizer) panel.SetAutoLayout(1) panel.SetupScrolling() #~ frame.SetSizer(sizer) #~ frame.SetAutoLayout(1) app.SetTopWindow(frame) #~ frame.SetIcon(wx.IconFromBitmap(svg_to_bitmap(logo, (32, 32), use_cairo = False))) #~ frame.SetSize(canvas.GetVirtualSize()) frame.Show() app.MainLoop()
class MyFrame(wx.Frame): def __init__(self, parent, ID, title): wx.Frame.__init__(self, parent, ID, title, wx.DefaultPosition, wx.Size(600, 400)) # Controls self.tin = wx.TextCtrl(self, size=wx.Size(600, 400), style=wx.TE_MULTILINE) self.test_panel = ScrolledPanel(self, size=wx.Size(600, 400)) self.test_panel.SetupScrolling() self.tin2 = wx.StaticText(self.test_panel) # Layout # -- Scrolled Window self.panel_sizer = wx.BoxSizer(wx.HORIZONTAL) self.panel_sizer.Add(self.tin2, 0, wx.EXPAND) self.test_panel.SetSizer(self.panel_sizer) self.panel_sizer.Fit(self.test_panel) # -- Main Frame self.inner_sizer = wx.BoxSizer(wx.HORIZONTAL) self.inner_sizer.Add(self.tin, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 50) self.inner_sizer.Add(self.test_panel, 1, wx.LEFT | wx.RIGHT | wx.EXPAND, 50) self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer.Add(self.inner_sizer, 1, wx.ALL | wx.EXPAND, 20) self.SetSizer(self.sizer) self.sizer.Fit(self) self.sizer.Layout() self.test_panel.SetAutoLayout(1) # Bind Events self.tin.Bind(wx.EVT_TEXT, self.TextChange) def TextChange(self, event): self.tin2.SetLabel(self.tin.GetValue()) self.test_panel.FitInside()
class ProjectPropertiesPanel(wx.Notebook): def AddSizerParams(self, parent, sizer, params): for idx, (name, label) in enumerate(params): border = 0 if idx == 0: border |= wx.TOP elif idx == len(params) - 1: border |= wx.BOTTOM st = wx.StaticText(parent, label=label) sizer.AddWindow(st, border=10, flag=wx.ALIGN_CENTER_VERTICAL | border | wx.LEFT) tc = wx.TextCtrl(parent, style=wx.TE_PROCESS_ENTER) setattr(self, name, tc) callback = self.GetTextCtrlChangedFunction(tc, name) self.Bind(wx.EVT_TEXT_ENTER, callback, tc) tc.Bind(wx.EVT_KILL_FOCUS, callback) sizer.AddWindow(tc, border=10, flag=wx.GROW | border | wx.RIGHT) def __init__(self, parent, controller=None, window=None, enable_required=True, scrolling=True): wx.Notebook.__init__(self, parent) self.Controller = controller self.ParentWindow = window self.Values = None # Project Panel elements self.ProjectPanel = ScrolledPanel(self, style=wx.TAB_TRAVERSAL) self.ProjectPanel.SetAutoLayout(1) if scrolling: self.ProjectPanel.SetupScrolling() projectpanel_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=5, vgap=15) projectpanel_sizer.AddGrowableCol(1) self.ProjectPanel.SetSizer(projectpanel_sizer) self.AddSizerParams( self.ProjectPanel, projectpanel_sizer, [("projectName", _('Project Name (required):')), ("projectVersion", _('Project Version (optional):')), ("productName", _('Product Name (required):')), ("productVersion", _('Product Version (required):')), ("productRelease", _('Product Release (optional):'))]) self.AddPage(self.ProjectPanel, _("Project")) # Author Panel elements self.AuthorPanel = ScrolledPanel(self, style=wx.TAB_TRAVERSAL) self.AuthorPanel.SetAutoLayout(1) if scrolling: self.AuthorPanel.SetupScrolling() authorpanel_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=4, vgap=15) authorpanel_sizer.AddGrowableCol(1) self.AuthorPanel.SetSizer(authorpanel_sizer) self.AddSizerParams(self.AuthorPanel, authorpanel_sizer, [("companyName", _('Company Name (required):')), ("companyURL", _('Company URL (optional):')), ("authorName", _('Author Name (optional):')), ("organization", _('Organization (optional):'))]) self.AddPage(self.AuthorPanel, _("Author")) # Graphics Panel elements self.GraphicsPanel = ScrolledPanel(self, style=wx.TAB_TRAVERSAL) self.GraphicsPanel.SetAutoLayout(1) if scrolling: self.GraphicsPanel.SetupScrolling() graphicpanel_sizer = wx.FlexGridSizer(cols=1, hgap=5, rows=4, vgap=5) graphicpanel_sizer.AddGrowableCol(0) graphicpanel_sizer.AddGrowableRow(3) self.GraphicsPanel.SetSizer(graphicpanel_sizer) pageSize_st = wx.StaticText(self.GraphicsPanel, label=_('Page Size (optional):')) graphicpanel_sizer.AddWindow(pageSize_st, border=10, flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.LEFT | wx.RIGHT) pageSize_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=5) pageSize_sizer.AddGrowableCol(1) graphicpanel_sizer.AddSizer(pageSize_sizer, border=10, flag=wx.GROW | wx.LEFT | wx.RIGHT) for name, label in [('PageWidth', _('Width:')), ('PageHeight', _('Height:'))]: st = wx.StaticText(self.GraphicsPanel, label=label) pageSize_sizer.AddWindow(st, border=12, flag=wx.ALIGN_CENTER_VERTICAL | wx.LEFT) sp = wx.SpinCtrl(self.GraphicsPanel, min=0, max=2**16, style=wx.TE_PROCESS_ENTER) setattr(self, name, sp) callback = self.GetPageSizeChangedFunction(sp, name) self.Bind(wx.EVT_TEXT_ENTER, callback, sp) sp.Bind(wx.EVT_KILL_FOCUS, callback) pageSize_sizer.AddWindow(sp, flag=wx.GROW) scaling_st = wx.StaticText(self.GraphicsPanel, label=_('Grid Resolution:')) graphicpanel_sizer.AddWindow(scaling_st, border=10, flag=wx.GROW | wx.LEFT | wx.RIGHT) scaling_nb = wx.Notebook(self.GraphicsPanel) graphicpanel_sizer.AddWindow(scaling_nb, border=10, flag=wx.GROW | wx.BOTTOM | wx.LEFT | wx.RIGHT) self.Scalings = {} for language, translation in [("FBD", _("FBD")), ("LD", _("LD")), ("SFC", _("SFC"))]: scaling_panel = wx.Panel(scaling_nb, style=wx.TAB_TRAVERSAL) scalingpanel_sizer = wx.FlexGridSizer(cols=2, hgap=5, rows=2, vgap=5) scalingpanel_sizer.AddGrowableCol(1) scaling_panel.SetSizer(scalingpanel_sizer) scaling_controls = [] for idx, (name, label) in enumerate([('XScale', _('Horizontal:')), ('YScale', _('Vertical:'))]): if idx == 0: border = wx.TOP else: border = wx.BOTTOM st = wx.StaticText(scaling_panel, label=label) scalingpanel_sizer.AddWindow(st, border=10, flag=wx.ALIGN_CENTER_VERTICAL | border | wx.LEFT) sp = wx.SpinCtrl(scaling_panel, min=0, max=2**16, style=wx.TE_PROCESS_ENTER) scaling_controls.append(sp) callback = self.GetScalingChangedFunction(sp, language, name) self.Bind(wx.EVT_TEXT_ENTER, callback, sp) sp.Bind(wx.EVT_KILL_FOCUS, callback) scalingpanel_sizer.AddWindow(sp, border=10, flag=wx.GROW | border | wx.RIGHT) self.Scalings[language] = scaling_controls scaling_nb.AddPage(scaling_panel, translation) self.AddPage(self.GraphicsPanel, _("Graphics")) # Miscellaneous Panel elements self.DescriptionPanel = ScrolledPanel(parent=self, name='DescriptionPanel', style=wx.TAB_TRAVERSAL) self.DescriptionPanel.SetAutoLayout(1) if scrolling: self.DescriptionPanel.SetupScrolling() DescriptionPanel_sizer = wx.FlexGridSizer(cols=1, hgap=5, rows=5, vgap=5) DescriptionPanel_sizer.AddGrowableCol(0) DescriptionPanel_sizer.AddGrowableRow(4) self.DescriptionPanel.SetSizer(DescriptionPanel_sizer) description_label = wx.StaticText( self.DescriptionPanel, label=_('Content Description (optional):')) DescriptionPanel_sizer.AddWindow(description_label, border=10, flag=wx.TOP | wx.LEFT) self.ContentDescription = wx.TextCtrl(self.DescriptionPanel, size=wx.Size(400, 200), style=wx.TE_MULTILINE | wx.TE_PROCESS_ENTER) self.Bind(wx.EVT_TEXT_ENTER, self.OnContentDescriptionChanged, self.ContentDescription) self.ContentDescription.Bind(wx.EVT_KILL_FOCUS, self.OnContentDescriptionChanged) DescriptionPanel_sizer.AddWindow(self.ContentDescription, border=10, flag=wx.ALIGN_CENTER_VERTICAL | wx.TOP | wx.LEFT | wx.RIGHT) self.AddPage(self.DescriptionPanel, _("Description")) for param in REQUIRED_PARAMS: getattr(self, param).Enable(enable_required) def RefreshView(self): if self.Controller is not None: self.SetValues(self.Controller.GetProjectProperties()) def SetValues(self, values): self.Values = values for item, value in values.items(): if item == "contentDescription": self.ContentDescription.SetValue(value) elif item == "pageSize": self.PageWidth.SetValue(value[0]) self.PageHeight.SetValue(value[1]) elif item == "scaling": for language, (x, y) in value.items(): if language in self.Scalings: self.Scalings[language][0].SetValue(x) self.Scalings[language][1].SetValue(y) else: tc = getattr(self, item, None) if tc is not None: tc.SetValue(value) def GetValues(self): values = {} for param in [ "projectName", "projectVersion", "productName", "productVersion", "productRelease", "companyName", "companyURL", "authorName", "organization" ]: value = getattr(self, param).GetValue() if param in REQUIRED_PARAMS or value != "": values[param] = value else: values[param] = None values["language"] = None content_description = self.ContentDescription.GetValue() if content_description != "": values["contentDescription"] = content_description else: values["contentDescription"] = None values["pageSize"] = (self.PageWidth.GetValue(), self.PageHeight.GetValue()) values["scaling"] = {} for language in ["FBD", "LD", "SFC"]: values["scaling"][language] = ( self.Scalings[language][0].GetValue(), self.Scalings[language][1].GetValue()) return values def GetTextCtrlChangedFunction(self, textctrl, name): def TextCtrlChangedFunction(event): if self.Controller is not None and self.Values is not None: old_value = self.Values.get(name) new_value = textctrl.GetValue() if name in REQUIRED_PARAMS and new_value == "": new_value = None if name == 'companyURL': if not URI_model.match(new_value): new_value = None dialog = wx.MessageDialog( self, _('Invalid URL!\n' 'Please enter correct URL address.'), _("Error"), wx.OK | wx.ICON_ERROR) dialog.ShowModal() dialog.Destroy() if old_value != new_value: self.Controller.SetProjectProperties( properties={name: new_value}) self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PROJECTTREE, PAGETITLES) wx.CallAfter(self.RefreshView) event.Skip() return TextCtrlChangedFunction def GetPageSizeChangedFunction(self, spinctrl, name): def PageSizeChangedFunction(event): if self.Controller is not None: if self.Values is not None: old_value = self.Values.get("pageSize") else: old_value = (0, 0) if name == 'PageWidth': new_value = (spinctrl.GetValue(), old_value[1]) else: new_value = (old_value[0], spinctrl.GetValue()) if old_value != new_value: self.Controller.SetProjectProperties( properties={"pageSize": new_value}) self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PAGETITLES, SCALING) wx.CallAfter(self.RefreshView) event.Skip() return PageSizeChangedFunction def GetScalingChangedFunction(self, spinctrl, language, name): def ScalingChangedFunction(event): if self.Controller is not None: old_value = (0, 0) if self.Values is not None: scaling = self.Values.get("scaling") if scaling is not None: old_value = scaling.get(language) if name == 'XScale': new_value = (spinctrl.GetValue(), old_value[1]) else: new_value = (old_value[0], spinctrl.GetValue()) if old_value != new_value: self.Controller.SetProjectProperties( properties={"scaling": { language: new_value }}) self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PAGETITLES, SCALING) wx.CallAfter(self.RefreshView) event.Skip() return ScalingChangedFunction def OnContentDescriptionChanged(self, event): if self.Controller is not None: if self.Values is not None: old_value = self.Values.get("contentDescription") else: old_value = None new_value = self.ContentDescription.GetValue() if new_value == "": new_value = None if old_value != new_value: self.Controller.SetProjectProperties( properties={"contentDescription": new_value}) self.ParentWindow._Refresh(TITLE, FILEMENU, EDITMENU, PAGETITLES) wx.CallAfter(self.RefreshView) event.Skip()
class ImportTextDialog(wx.Dialog): requiredVariables = {'x':'x position [nm]', 'y':'y position [nm]'} recommendedVariables = {'A':'amplitude of Gaussian', 't':'time [frames]', 'sig':'std. deviation of Gaussian [nm]', 'error_x':'fit error in x direction [nm]'} niceVariables = {'error_y':'fit error in y direction [nm]'} def __init__(self, parent, textFileName): wx.Dialog.__init__(self, parent, title='Import data from text file') self.colNames, self.dataLines = self.TextFileHeaderParse(textFileName) sizer1 = wx.BoxSizer(wx.VERTICAL) #sizer2 = wx.BoxSizer(wx.HORIZONTAL) sizer1.Add(wx.StaticText(self, -1, 'Please assign variable names to each column. Some variable names must be present for the program to function correctly'), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.GenerateDataGrid(sizer1) sizer2 = wx.BoxSizer(wx.HORIZONTAL) self.stRequiredNotPresent = wx.StaticText(self, -1, 'Required variables not yet defined:\n') sizer2.Add(self.stRequiredNotPresent, 1, wx.ALL, 5) self.stRecommendedNotPresent = wx.StaticText(self, -1, 'Recommended variables not yet defined:\n') sizer2.Add(self.stRecommendedNotPresent, 1, wx.ALL, 5) sizer1.Add(sizer2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL|wx.EXPAND, 5) sizer2 = wx.BoxSizer(wx.HORIZONTAL) sizer2.Add(wx.StaticText(self, -1, 'Pixel size [nm]:'), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.tPixelSize = wx.TextCtrl(self, -1, '1.0') sizer2.Add(self.tPixelSize, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) sizer1.Add(sizer2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL|wx.EXPAND, 5) btSizer = wx.StdDialogButtonSizer() self.btnOK = wx.Button(self, wx.ID_OK) self.btnOK.SetDefault() self.btnOK.Enable(False) btSizer.AddButton(self.btnOK) btn = wx.Button(self, wx.ID_CANCEL) btSizer.AddButton(btn) btSizer.Realize() sizer1.Add(btSizer, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5) self.CheckColNames() self.SetSizer(sizer1) sizer1.Fit(self) def TextFileHeaderParse(self, filename): n = 0 commentLines = [] dataLines = [] fid = open(filename, 'r') if filename.endswith('.csv'): delim = ',' else: delim = None #whitespace while n < 10: line = fid.readline() if line.startswith('#'): #check for comments commentLines.append(line[1:]) elif not isnumber(line.split(delim)[0]): #or textual header that is not a comment commentLines.append(line) else: dataLines.append(line.split(delim)) n += 1 self.numCommentLines = len(commentLines) numCols = len(dataLines[0]) #print commentLines #print commentLines[-1].split(delim), len(commentLines[-1].split(delim)), numCols if len(commentLines) > 0 and len(commentLines[-1].split(delim)) == numCols: colNames = commentLines[-1].split(delim) else: colNames = ['column_%d' % i for i in range(numCols)] return colNames, dataLines def CheckColNames(self): reqNotDef = [var for var in self.requiredVariables.keys() if not var in self.colNames] if len(reqNotDef) > 0: self.btnOK.Enable(False) sreq = 'Required variables not yet defined:\n' for k in reqNotDef: sreq += '\n\t%s\t-\t%s' % (k, self.requiredVariables[k]) self.stRequiredNotPresent.SetForegroundColour(wx.RED) else: self.btnOK.Enable(True) sreq = 'All required variables are defined\n' self.stRequiredNotPresent.SetForegroundColour(wx.GREEN) self.stRequiredNotPresent.SetLabel(sreq) recNotDef = [var for var in self.recommendedVariables.keys() if not var in self.colNames] if len(recNotDef) > 0: sreq = 'Recomended variables not yet defined:\n' for k in recNotDef: sreq += '\n\t%s\t-\t%s' % (k, self.recommendedVariables[k]) self.stRecommendedNotPresent.SetForegroundColour(wx.Colour(200, 150, 0)) else: sreq = 'All recommended variables are defined\n' self.stRecommendedNotPresent.SetForegroundColour(wx.GREEN) self.stRecommendedNotPresent.SetLabel(sreq) def GenerateDataGrid(self, sizer): vsizer = wx.StaticBoxSizer(wx.StaticBox(self, -1, 'Column names and preview:')) self.scrollW = ScrolledPanel(self, -1, size=(800, 150)) self.comboIDs = [] self.combos = [] fgSizer = wx.FlexGridSizer(1+len(self.dataLines), len(self.colNames), 4, 4) for cn in self.colNames: id = wx.NewId() self.comboIDs.append(id) cb = wx.ComboBox(self.scrollW, id, size=(120, -1), choices=[cn]+ list(self.requiredVariables.keys()) +list(self.recommendedVariables.keys()) + list(self.niceVariables.keys())) self.combos.append(cb) cb.SetSelection(0) cb.Bind(wx.EVT_COMBOBOX, self.OnColNameChange) cb.Bind(wx.EVT_TEXT, self.OnColNameChange) fgSizer.Add(cb) for dl in self.dataLines: for de in dl: fgSizer.Add(wx.StaticText(self.scrollW, -1, de)) self.scrollW.SetSizer(fgSizer) self.scrollW.SetAutoLayout(True) self.scrollW.SetupScrolling() vsizer.Add(self.scrollW, 0, wx.EXPAND|wx.ALL,5) sizer.Add(vsizer, 0, wx.EXPAND|wx.ALL,5) def OnColNameChange(self, event): colNum = self.comboIDs.index(event.GetId()) self.colNames[colNum] = self.combos[colNum].GetValue() self.CheckColNames() def GetFieldNames(self): return self.colNames def GetNumberComments(self): return self.numCommentLines def GetPixelSize(self): return float(self.tPixelSize.GetValue())
class InjectionInputsPanel(pdsim_panels.PDPanel): """ The container panel for all the injection ports and injection data """ def __init__(self, parent, **kwargs): pdsim_panels.PDPanel.__init__(self, parent, **kwargs) #Now we are going to put everything into a scrolled window main_sizer = wx.BoxSizer(wx.VERTICAL) self.scrolled_panel = ScrolledPanel(self, size=(-1, -1), style=wx.TAB_TRAVERSAL, name="panel1") self.scrolled_panel.SetScrollbars(1, 1, 1, 1) self.scrolled_panel.SetupScrolling() #Add the header row of buttons self.View = wx.Button(self.scrolled_panel, label='View') self.View.Bind(wx.EVT_BUTTON, self.OnView) self.AddInjection = wx.Button(self.scrolled_panel, label='Add Injection Line') self.AddInjection.Bind(wx.EVT_BUTTON, self.OnAddInjection) self.PlotExistence = wx.Button(self.scrolled_panel, label='Plot Existence') self.PlotExistence.Bind(wx.EVT_BUTTON, self.OnPlotExistence) buttons_sizer = wx.BoxSizer(wx.HORIZONTAL) buttons_sizer.Add(self.AddInjection) buttons_sizer.Add(self.View) buttons_sizer.Add(self.PlotExistence) sizer = wx.FlexGridSizer(cols=1) sizer.Add(buttons_sizer) sizer.AddSpacer(10) sizer.Layout() self.scrolled_panel.SetAutoLayout(1) #Do the layout of all the panels self.scrolled_panel.SetSizer(sizer) main_sizer.Add(self.scrolled_panel, 1, wx.EXPAND) self.SetSizer(main_sizer) main_sizer.Layout() #Set some local variables self.Nterms = 0 self.Lines = [] def OnAddInjection(self, event=None): """ Add an injection line to the injection panel """ IE = InjectionElementPanel(self.scrolled_panel, self.Nterms + 1) #Put the panel within the scrolled panel and refresh self.scrolled_panel.GetSizer().Add(IE, 0) self.scrolled_panel.FitInside() self.GetSizer().Layout() #Update the local variables self.Lines.append(IE) self.Nterms += 1 self.Refresh() def remove_all(self): while self.Lines: self.RemoveInjection(self.Lines[0]) def RemoveInjection(self, injection): """ Remove the given injection term """ self.Lines.remove(injection) injection.Destroy() self.Nterms -= 1 #Renumber the injection panels that are contained in scrolled_panel I = 1 for child in self.scrolled_panel.Children: if isinstance(child, InjectionElementPanel): child.SizerBox.SetLabel("Injection line #" + str(I)) I += 1 self.GetSizer().Layout() self.scrolled_panel.FitInside() self.Refresh() def OnView(self, event): geo = self.GetTopLevelParent().MTB.InputsTB.panels[0].Scroll.geo SAF = ScrollAnimForm(geo, start=False) #IEPs are children that are instances of InjectionElementPanel class IEPs = [ child for child in self.scrolled_panel.Children if isinstance(child, InjectionElementPanel) ] for IEP in IEPs: for child in IEP.Children: if isinstance(child, InjectionPortPanel): # Get the values from the panel vals = child.get_values() # Overlay the port on the scroll wrap plot scroll_geo.overlay_injection_port(0, geo, vals['phi'], SAF.ax, vals['involute'], rport=vals['D'] / 2, offset=vals['offset']) SAF.start() SAF.Show() def OnPlotExistence(self, event=None): """ Plot a 2D line plot showing which control volume is connected to each injection port as a function of the crank angle """ import pylab import numpy as np _Scroll = self.GetTopLevelParent().MTB.InputsTB.panels[0].Scroll Iport = 1 #IEPs are children that are instances of InjectionElementPanel class IEPs = [ child for child in self.scrolled_panel.Children if isinstance(child, InjectionElementPanel) ] for IEP in IEPs: for child in IEP.Children: if isinstance(child, InjectionPortPanel): #Get the values from the port panel v = child.get_values() partner_list = [] theta = np.linspace(0, 2 * pi, 1000) for th in theta: partner_list.append( _Scroll._get_injection_CVkey( v['phi'], th, v['involute'])) #Find the break points in each segment dividers = [ i for i in range(len(theta) - 1) if not partner_list[i] == partner_list[i + 1] ] #Add end and beginning indices dividers = [0] + dividers + [len(theta) - 1] for i in range(len(dividers) - 1): L = dividers[i] R = dividers[i + 1] M = int((L + R) / 2) pylab.plot(np.r_[theta[L], theta[R]], np.r_[Iport, Iport]) pylab.plot(np.r_[theta[L], theta[L]], np.r_[Iport - 0.02, Iport + 0.02], 'k') pylab.plot(np.r_[theta[R], theta[R]], np.r_[Iport - 0.02, Iport + 0.02], 'k') pylab.text(theta[M], Iport + .02, partner_list[M], ha='center', va='bottom') #Increase the counter Iport += 1 pylab.xticks([0, pi / 2, pi, 3 * pi / 2, 2 * pi], [0, r'$\pi/2$', r'$\pi$', r'$3\pi/2$', r'$2\pi$']) pylab.xlim(0, 2 * pi) pylab.ylim(0.5, Iport - 1 + 0.5) pylab.yticks(range(1, Iport + 1)) pylab.show() def build_from_configfile(self, config): """ Get parameters from the configfile section for this plugin Parameters ---------- config : yaml configuration section for the plugin """ if config: self.remove_all() for line in config: # Add an injection line panel self.OnAddInjection() #Get a pointer to the last IEP (the one just added) IEP = self.Lines[-1] #Set the line length in the GUI [m] IEP.Lval.SetValue(str(line['Length'])) #Set the line ID in the GUI IEP.IDval.SetValue(str(line['ID'])) #Set the State in the GUI State = line['inletState'] IEP.state.set_state(State['Fluid'], T=State['T'], D=State['rho']) if 'ports' in line and line['ports']: for i, port in enumerate(line['ports']): if i > 0: IEP.OnAddPort() # Get a pointer to the port panel portpanel = IEP.ports_list[-1] # Set the values in the panel portpanel.set_values(port) def get_additional_parametric_terms(self): #: the list of terms _T = [] #IEPs are children of injection_panel that are instances of InjectionElementPanel class IEPs = [ child for child in self.scrolled_panel.Children if isinstance(child, InjectionElementPanel) ] for i, IEP in enumerate(IEPs): I = str(i + 1) _T += [ dict(attr='injection_state_pressure_' + I, text='Injection pressure #' + I + ' [kPa]', parent=self), dict(attr='injection_state_sat_temp_' + I, text='Injection saturated temperature (dew) #' + I + ' [K]', parent=self), dict(attr='injection_state_temp_' + I, text='Injection temperature #' + I + ' [K]', parent=self), dict(attr='injection_state_superheat_' + I, text='Injection superheat #' + I + ' [K]', parent=self), ] Ports = [ c for c in IEP.Children if isinstance(c, InjectionPortPanel) ] for j, child in enumerate(Ports): J = str(j + 1) _T += [ dict(attr='injection_phi_' + I + '_' + J, text='Injection port angle #' + I + ':' + J + ' [rad]', parent=self) ] return _T def apply_additional_parametric_terms(self, attrs, vals, panel_items): """ Set the terms in the injection panel based on the additional parametric terms provided by the get_additional_parametric_terms() function """ def apply_line_terms(attrs, vals): def is_int(i): """ Returns True if it is an integer """ try: i = int(i) return True except ValueError: return False def is_line_term(attr): """ Check if it is a line type term of the form injection_xxxxx_1' and is not a port term of the form injection_xxxxx_1_1 """ if not attr.startswith('injection'): return False #If there are no underscores, return false if len(attr.rsplit('_', 1)) == 1: return False #Try to split twice attr, i, j = attr.rsplit('_', 2) # If the far right one is an integer and the left part isn't you are # ok, its an injection line if not is_int(i) and is_int(j): return True else: return False # First check about the injection state; if two state related terms are # provided, use them to fix the injection state inj_state_params = [(par, val) for par, val in zip(attrs, vals) if is_line_term(par)] num_inj_state_params = len(inj_state_params) for i in range(len(self.Lines)): #Find the injection state terms that apply for this line state_params = [ (par, val) for par, val in zip(attrs, vals) if par.find('state') > -1 and par.endswith(str(i + 1)) ] num_state_params = len(state_params) #Get a copy of the state from the StatePanel inletState = self.Lines[i].state.GetState() if num_state_params > 0: #Unzip the parameters (List of tuples -> tuple of lists) state_attrs, state_vals = zip(*state_params) if num_state_params == 2: # Remove all the entries that correspond to the injection state - # we need them and don't want to set them in the conventional way for a in state_attrs: vals.pop(attrs.index(a)) attrs.pop(attrs.index(a)) #: The string representation of the index (1-based) I = str(i + 1) #Temperature and pressure provided if 'injection_state_temp_' + I in state_attrs and 'injection_state_pressure_' + I in state_attrs: injection_temp = state_vals[state_attrs.index( 'injection_state_temp_' + I)] injection_pressure = state_vals[state_attrs.index( 'injection_state_pressure_' + I)] self.Lines[i].state.set_state(inletState.Fluid, T=injection_temp, P=injection_pressure) #Dew temperature and superheat provided elif 'injection_state_sat_temp_' + I in state_attrs and 'injection_state_superheat_' + I in state_attrs: injection_sat_temp = state_vals[state_attrs.index( 'injection_state_sat_temp_' + I)] injection_superheat = state_vals[state_attrs.index( 'injection_state_superheat_' + I)] injection_temp = injection_sat_temp + injection_superheat import CoolProp.CoolProp as CP injection_pressure = CP.PropsSI( 'P', 'T', injection_sat_temp, 'Q', 1.0, inletState.Fluid) / 1000.0 self.Lines[i].state.set_state(inletState.Fluid, T=injection_temp, P=injection_pressure) else: raise ValueError( 'Invalid combination of injection states: ' + str(state_attrs)) elif num_inj_state_params == 1: import textwrap string = textwrap.dedent(""" Sorry but you need to provide two variables for the injection state in parametric table to fix the state. If you want to just modify the saturated temperature, add the superheat as a variable and give it one element in the parametric table """) dlg = wx.MessageDialog(None, string) dlg.ShowModal() dlg.Destroy() raise ValueError( 'Must provide two state variables in the parametric table for injection line' ) elif num_inj_state_params > 2: raise ValueError( 'Only two inlet state parameters can be provided in parametric table' ) return attrs, vals def apply_port_terms(attrs, vals): phi_params = [(par, val) for par, val in zip(attrs, vals) if par.startswith('injection_phi')] num_phi_params = len(phi_params) if num_phi_params > 0: #Unzip the parameters (List of tuples -> tuple of lists) phi_attrs, phi_vals = zip(*phi_params) # Remove all the entries that correspond to the angles # we need them and don't want to set them in the conventional way for a in phi_attrs: i = attrs.index(a) vals.pop(i) attrs.pop(i) for attr, val in zip(phi_attrs, phi_vals): # Term might look like something like 'injection_phi_1_2' # i would be 0, j would be 1 #indices are zero-based j = int(attr.rsplit('_', 1)[1]) - 1 i = int(attr.rsplit('_', 2)[1]) - 1 self.Lines[i].ports_list[j].phi_inj_port.SetValue(str(val)) return attrs, vals #Apply all the line terms and get back the lists attrs, vals = apply_line_terms(attrs, vals) #Apply all the line terms and get back the lists attrs, vals = apply_port_terms(attrs, vals) return attrs, vals
class EditDialog(wx.Dialog): def __init__(self, edit_url): super().__init__(parent=None, title=preset.message["edit_title"] + "[" + edit_url.URL_Name + "]", size=(700, 590), style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER) self.url = edit_url self.scrolled_panel = ScrolledPanel(self) self.scrolled_panel.SetupScrolling() self.left_box_sizer = wx.BoxSizer(wx.VERTICAL) self.right_box_sizer = wx.BoxSizer(wx.VERTICAL) max_length = 0 for item in preset.label_dictionary: label_length = len(preset.label_dictionary[item]) if label_length > max_length: max_length = label_length self.attribute_list = [] for index, item in enumerate(edit_url.to_list()): element_value = edit_url.get_position(index) if isinstance(element_value, datetime.datetime): item_value = utils.date_to_string(element_value) else: item_value = str(element_value) self.attribute_list.append( wx.TextCtrl(self.scrolled_panel, value=item_value)) dialog_place = "left" if index > 21: dialog_place = "right" self.add_widgets(edit_url.get_label(str(index)), self.attribute_list[index], dialog_place, max_length) cancel_button = wx.Button(self, id=wx.ID_CANCEL, label=preset.message["cancel_button"]) save_button = wx.Button(self, id=wx.ID_OK, label=preset.message["edit_save"]) save_button.Bind(wx.EVT_BUTTON, self.on_save) horizontal_box_sizer = wx.BoxSizer(wx.HORIZONTAL) horizontal_box_sizer.Add(self.left_box_sizer, 1, wx.EXPAND, 1) horizontal_box_sizer.Add(self.right_box_sizer, 1, wx.EXPAND, 1) self.scrolled_panel.SetSizer(horizontal_box_sizer) self.scrolled_panel.SetAutoLayout(1) button_box_sizer = wx.BoxSizer(wx.HORIZONTAL) button_box_sizer.Add(save_button, 1) button_box_sizer.Add(cancel_button, 1) main_box_sizer = wx.BoxSizer(wx.VERTICAL) main_box_sizer.Add(self.scrolled_panel, 1, wx.EXPAND, 1) main_box_sizer.Add(button_box_sizer, 0, wx.ALL | wx.EXPAND, 0) self.SetSizer(main_box_sizer) def add_widgets(self, text_label, text_ctrl, dialog_place, max_length): spaces_gap = max_length - len(text_label) text_label = text_label + " " * spaces_gap + ":" static_text = wx.StaticText(self.scrolled_panel, label=text_label, size=(max_length * 8, -1)) static_text.SetFont( wx.Font(8, wx.TELETYPE, wx.NORMAL, wx.BOLD, underline=True)) static_bullet = wx.StaticText(self.scrolled_panel, label=" °", size=(14, -1)) static_bullet.SetFont(wx.Font(8, wx.TELETYPE, wx.NORMAL, wx.BOLD)) box_sizer_horizontal = wx.BoxSizer(wx.HORIZONTAL) box_sizer_horizontal.Add(static_bullet, 0, wx.ALIGN_CENTER_VERTICAL, 0) box_sizer_horizontal.Add(static_text, 0, wx.ALIGN_CENTER_VERTICAL, 0) box_sizer_horizontal.Add(text_ctrl, 1, wx.ALL, 0) if dialog_place == "left": self.left_box_sizer.Add(box_sizer_horizontal, 1, wx.EXPAND, 1) else: self.right_box_sizer.Add(box_sizer_horizontal, 1, wx.EXPAND, 1) def on_save(self, event): save_list = [] for element in self.attribute_list: save_list.append(element.GetValue()) self.url.set_data(save_list) self.EndModal(event.EventObject.Id)
def __init__(self, parent, exc_type, exc_value, exc_info, exc_msg): wx.Dialog.__init__(self, parent, title="fr0st has encountered an error") self.exc_msg = exc_msg self.show_label = "Show Error Report >>" self.hide_label = "Hide Error Report <<" self.collapsible = wx.CollapsiblePane(self, label=self.show_label) pane = self.collapsible.GetPane() scrolled = ScrolledPanel(pane, size=(500, 250), style = wx.TAB_TRAVERSAL|wx.SUNKEN_BORDER) text = wx.StaticText(scrolled, label=exc_msg) copy_clipboard = wx.Button(pane, label='Copy to clipboard') self.Bind(wx.EVT_BUTTON, self.OnCopyClipboard, copy_clipboard) sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(text, 1, wx.EXPAND) scrolled.SetSizer(sizer) scrolled.SetAutoLayout(True) scrolled.SetupScrolling() sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(copy_clipboard, 0, wx.ALIGN_RIGHT|wx.RIGHT, 15) sizer.Add(scrolled, 1, wx.EXPAND|wx.ALL, 15) pane.SetSizer(sizer) sizer = wx.BoxSizer(wx.VERTICAL) static = wx.StaticText(self, label="fr0st has encountered an error and must exit.") static.Wrap(500) sizer.Add(static, 0, wx.EXPAND|wx.ALL, 5) static = wx.StaticText(self, label="%s: %s" % ( exc_type.__name__, str(exc_value)), style=wx.BORDER_SUNKEN) static.Wrap(500) sizer.Add(static, 0, wx.EXPAND|wx.ALL, 5) static = wx.StaticText(self, label="If this problem persists, please consider posting " "the error report to the mailing list.") static.Wrap(500) sizer.Add(static, 0, wx.EXPAND|wx.ALL, 5) sizer.Add(self.collapsible, 0, wx.EXPAND|wx.ALL, 5) quit_button = wx.Button(self, label='Exit fr0st', id=wx.ID_EXIT) self.Bind(wx.EVT_BUTTON, self.OnExitFr0st, quit_button) ok_button = wx.Button(self, label='OK', id=wx.ID_OK) self.Bind(wx.EVT_BUTTON, self.OnOK, ok_button) button_sizer = wx.BoxSizer(wx.HORIZONTAL) button_sizer.Add(ok_button, 0, wx.ALL, 5) button_sizer.Add(quit_button, 0, wx.ALL, 5) #buttons = self.CreateButtonSizer(wx.OK) #buttons = self.CreateSeparatedButtonSizer(wx.OK) sizer.Add(button_sizer, 0, wx.ALIGN_RIGHT) self.SetSizerAndFit(sizer)
class DubList(wx.Frame): class Node(wx.TextCtrl): def __init__(self, parent, id, value, pos, size, style, validator, name, listPtr): super(DubList.Node, self).__init__(parent, id, value, pos, size, style, validator, name) print "Node" self.nodesizer = wx.FlexGridSizer(cols=2, vgap=1, hgap=1) self.popButton = wx.Button(self, wx.ID_ANY, "K", wx.DefaultPosition, (11, 11)) self.pushButton = wx.Button(self, wx.ID_ANY, "P", wx.DefaultPosition + (0, 13), (11, 11)) self.listManager = listPtr self.next = None self.prev = None self.val = None self.point = self.GetPosition() self.Bind(wx.EVT_BUTTON, listPtr.onRemove, self.popButton) self.Bind(wx.EVT_BUTTON, listPtr.onPush, self.pushButton) def __init__(self, parent, id, title, pos, size, style, name): super(DubList, self).__init__(parent, id, title, pos, size, style, name) masterSizer = wx.BoxSizer(wx.VERTICAL) #self.SetSizeHints(wx.DefaultSize, wx.DefaultSize) self.nodeNumbers = 0 #self.listWindow = scrolledpanel(self, wx.ID_ANY, self.Position, self.Size, wx.VSCROLL, "list window") self.listWindow = ScrolledPanel(self, wx.ID_ANY, self.GetPosition(), self.GetSize(), wx.TAB_TRAVERSAL | wx.VSCROLL, "list window") self.listWindow.SetupScrolling(0, 1, 0, 20, 1, 1) #self.listWindow.SetScrollRate(5,5) not needced self.listOfNodes = [] self.mysizer = wx.GridBagSizer(5, 5) #self.mysizer = wx.BoxSizer(wx.VERTICAL) button = wx.Button(self.listWindow, wx.ID_ANY, "push new node", wx.DefaultPosition + (150, 0), wx.DefaultSize, 0, wx.DefaultValidator, "make") button.Bind(wx.EVT_BUTTON, self.buttonDown, button) button0 = wx.Button(self.listWindow, wx.ID_ANY, "pop last node", wx.DefaultPosition + (260, 0), wx.DefaultSize, wx.BU_EXACTFIT, wx.DefaultValidator, "take") button0.Bind(wx.EVT_BUTTON, self.button0Down, button0) #layout #self.mysizer.SetSizeHints(self.listWindow) not needed #self.mysizer.Add(button, 0,0,1,None) #self.mysizer.Add(button0, 0,0,1,None) self.mysizer.Add(button, (0, 1), (0, 0), 0, 1, "addButton") self.mysizer.Add(button0, (1, 1), (0, 0), 0, 1, "removeButton") self.listWindow.SetSizer(self.mysizer) self.mysizer.Fit(self.listWindow) self.listWindow.SetAutoLayout(1) def onRemove(self, event): button = event.GetEventObject() button = button.GetParent() print "middle pop", button.val #patch pointers of adjacent Nodes if button.prev is not None: button.prev.next = button.next if button.next is not None: button.next.prev = button.prev #iter = button.next position = self.mysizer.FindItem(button) #find GBSizerItem gap = position.GetPos() iter = button self.mysizer.Detach(button) #push all the itesm below the target node up one unit while (iter): if (iter.next is not None): newgap = self.mysizer.GetItemPosition(iter.next) self.mysizer.SetItemPosition(iter.next, gap) gap = newgap iter = iter.next else: break self.listOfNodes.remove(button) self.mysizer.FitInside(self.listWindow) self.mysizer.Layout() button.Destroy() def onPush(self, event): #get infor for shifter button = event.GetEventObject() button = button.GetParent() print "middle push", button.val namestring = "button" + str(self.nodeNumbers) #get index of node being clicked print "index", 2 + self.listOfNodes.index(button) targetIndex = self.listOfNodes.index(button) targetposition = self.mysizer.GetItemPosition(button) targetposition.Row += 1 #push new node at btome of clicked node, and shift whole list bewlow it, down one Unit firstNode = self.listOfNodes[targetIndex] # head of list #shifter #walk is how many nodes we need to push down, or "walk" to walk = 0 while firstNode.next is not None: #iter until eol firstNode = firstNode.next walk += 1 while walk: lastPos = self.mysizer.GetItemPosition(firstNode) lastPos.row += 1 self.mysizer.SetItemPosition(firstNode, lastPos) firstNode = firstNode.prev walk -= 1 #malloc and push create = self.Node(self.listWindow, wx.ID_ANY, namestring, wx.DefaultPosition, wx.DefaultSize, 0, wx.DefaultValidator, namestring, self) if firstNode.next: firstNode.next.prev = create create.next = firstNode.next firstNode.next = create create.prev = firstNode self.listOfNodes.insert(targetIndex + 1, create) self.nodeNumbers += 1 self.mysizer.Add(create, targetposition, (0, 0), 0, 1, namestring) self.mysizer.FitInside(self.listWindow) self.listWindow.ScrollChildIntoView(create) print self.nodeNumbers def buttonDown(self, event): print "LIST: push pressed" namestring = "button" # a list if len(self.listOfNodes) is not 0: firstNode = self.listOfNodes[0] # head of list while firstNode.next is not None: #iter until eol firstNode = firstNode.next namestring += str(self.nodeNumbers) #create = Node(self.listWindow, wx.ID_ANY,namestring,firstNode.point + (0,25), wx.DefaultSize, 0, wx.DefaultValidator, namestring) create = self.Node(self.listWindow, wx.ID_ANY, namestring, firstNode.point, wx.DefaultSize, 0, wx.DefaultValidator, namestring, self) create.val = len(self.listOfNodes) firstNode.next = create create.prev = firstNode # no list else: namestring += str(len(self.listOfNodes)) create = self.Node(self.listWindow, wx.ID_ANY, namestring, wx.DefaultPosition, wx.DefaultSize, 0, wx.DefaultValidator, namestring, self) create.val = len(self.listOfNodes) create.parent = self self.nodeNumbers += 1 #self.mysizer.Add(create,0,0,1,namestring) #boxsizer add self.mysizer.Add(create, (1 + len(self.listOfNodes), 2), (0, 0), 0, 1, namestring) self.listOfNodes.append(create) self.mysizer.FitInside(self.listWindow) #self.listWindow.SetFocus()not needed self.listWindow.ScrollChildIntoView(create) #self.listWindow.Refresh() not needed #self.listWindow.Update() not needed #self.mysizer.Layout() not needed print self.nodeNumbers def button0Down(self, event): print "LIST: pop pressed" if len(self.listOfNodes) is not 0: lastNode = self.listOfNodes[len(self.listOfNodes) - 1] #grab last node try: prev = lastNode.prev prev.next = None except: print "last node" self.mysizer.Detach(lastNode) self.listOfNodes.remove(lastNode) lastNode.Destroy() self.mysizer.FitInside(self.listWindow) self.mysizer.Layout() else: print "no list"
class CombinePage(wx.Panel): """ A single page of the CombineInterface's Listbook It is very important that this is a wx.Panel with a sizer which contains the ScrolledPanel. Otherwise, the ScrolledPanel will not have a scroll bar, though it is still possible to scroll using the scroll wheel. """ def __init__(self, parent, id, color_set, colors, pattern_size, min_size, counts_per_colorset=None, is_totals_page=False): super(CombinePage, self).__init__(parent, id) outersizer = wx.BoxSizer(wx.VERTICAL) self.scrolledpanel = ScrolledPanel(self, -1, style=wx.TAB_TRAVERSAL) self.sizer = wx.BoxSizer(wx.VERTICAL) # Display a max of 100 color sets for each set size max_sets_coef = 100/math.log(pattern_size) count_by_size = {} # compute inclusion exclusion coefficients in_ex = [] for n_colors in range(pattern_size, -1, -1): # For inclusion/exclusion principle, we either need to add or # subtract the count for a specific set of colors in order to avoid # double counting. We count the number of times a color combination # of size numColors was counted in the color combinations of size # greater than numColors and adjust our count accordingly. discrepancy = pattern_size - n_colors remaining_colors = len(colors) - n_colors in_ex_modifier = 1 - sum([choose(remaining_colors, discrepancy-i) * mod for i, mod in enumerate(in_ex)]) in_ex.append(in_ex_modifier) # If this is the totals page if is_totals_page: c_sets_by_size = [] # Add up counts for each size of color sets for c_set, count in counts_per_colorset.iteritems(): len_c_set = len(c_set) if len_c_set in count_by_size: count_by_size[len_c_set] += count else: count_by_size[len_c_set] = count # Add color sets from CONCUSS's output instead of generating them again for i in range(pattern_size, min_size - 1, -1): c_sets_by_size.append([set(colorset) for colorset in counts_per_colorset.keys() if len(colorset) == i]) else: self.CSG = CombineSetGenerator(color_set, colors, pattern_size, min_size) c_sets_by_size = self.CSG.get_color_sets() total = 0 add = len(c_sets_by_size) % 2 == 1 for c_sets in c_sets_by_size: max_sets = int(max_sets_coef*math.log(len(c_sets[0]))) inexterm = InExTermWidget(self.scrolledpanel, c_sets, in_ex, colors, pattern_size, add, max_sets, count_by_size, totals_term=is_totals_page) self.sizer.Add(inexterm, 0, wx.EXPAND|wx.BOTTOM, 12) total += inexterm.total add = not add text = wx.StaticText(self.scrolledpanel, -1, 'Final total: ' + str(total)) modified_font=text.GetFont() modified_font.SetPixelSize((20,20)) modified_font.SetWeight(wx.FONTWEIGHT_BOLD) text.SetFont(modified_font) self.sizer.Add(text, 0, wx.RIGHT|wx.LEFT|wx.ALIGN_RIGHT, 12) self.scrolledpanel.SetSizer(self.sizer) self.scrolledpanel.SetAutoLayout(1) self.scrolledpanel.SetupScrolling(scroll_x=False) outersizer.Add(self.scrolledpanel, 1, wx.EXPAND) self.SetSizer(outersizer)
class ConfigPage(Panel): """ConfigPage holds the GUI for a single tab pane""" config = None grid_sizer = None main_sizer = None scrolled_panel = None def __init__(self, parent, config): Panel.__init__(self, parent=parent, id=ID_ANY) self.config = config self.header_font = Font(FontInfo(24).Bold()) self.construct_gui() def construct_horizontal_rule(self): """Adds a horizontal rule to the grid""" rule = StaticLine( self.scrolled_panel, style=LI_HORIZONTAL, size=(-1, 2) ) self.grid_sizer.Add( rule, proportion=1, flag=EXPAND | TOP | BOTTOM, border=10 ) def construct_docs_label(self, kind, value): """Constructs a documentation label""" sizer = BoxSizer(HORIZONTAL) label = HidableAutoWrapStaticText( parent=self.scrolled_panel, label=value, kind=kind, ) sizer.Add(label, -1, EXPAND) self.grid_sizer.Add(sizer, -1, EXPAND) def construct_entry_label(self, value): """Creates the primary entry label""" sizer = BoxSizer(HORIZONTAL) label = StaticText( self.scrolled_panel, label=value, style=ALIGN_LEFT ) label.SetFont(self.header_font) sizer.Add(label, -1, EXPAND) self.grid_sizer.Add(sizer, -1, EXPAND) def construct_entry_control(self, entry): """Creates the primary entry control""" if 'boolean' == entry.var_type: control = CheckBox( self.scrolled_panel, name=entry.key_name ) control.SetValue(entry.current) elif 'number' == entry.var_type: control = SpinCtrl( self.scrolled_panel, name=entry.key_name, ) control.SetValue(entry.current) else: control = TextCtrl( self.scrolled_panel, value=str(entry.current), name=entry.key_name, size=(-1, -1) ) self.grid_sizer.Add(control, -1, EXPAND) def construct_entry_row(self, entry, index=0): """Constructs all the necessary rows for a single entry""" if index > 0: self.construct_horizontal_rule() self.construct_entry_label(entry.key_name) if entry.help_value: self.construct_docs_label('help_value', entry.help_value) self.construct_entry_control(entry) if entry.man: self.construct_docs_label('man', entry.man) def construct_gui(self): """Constructs the page GUI""" self.scrolled_panel = ScrolledPanel(self) self.scrolled_panel.SetAutoLayout(1) self.scrolled_panel.SetupScrolling() self.main_sizer = BoxSizer(HORIZONTAL) self.grid_sizer = FlexGridSizer(1, 10, 10) for index, entry in enumerate(self.config): self.construct_entry_row(entry, index) self.grid_sizer.AddGrowableCol(0, 1) scroll_sizer = BoxSizer(HORIZONTAL) scroll_sizer.Add(self.grid_sizer, 1, EXPAND | ALL, 20) self.scrolled_panel.SetSizer(scroll_sizer) self.main_sizer.Add(self.scrolled_panel, 1, EXPAND) self.SetSizer(self.main_sizer)
class ColumnMappingDialog(wx.Dialog): requiredVariables = {'x': 'x position [nm]', 'y': 'y position [nm]'} recommendedVariables = { 'A': 'amplitude of Gaussian', 't': 'time [frames]', 'sig': 'std. deviation of Gaussian [nm]', 'error_x': 'fit error in x direction [nm]' } niceVariables = { 'z': 'z position [nm]', 'error_y': 'fit error in y direction [nm]', 'error_z': 'fit error in z direction [nm]' } fileType = 'column source' # string to indicate file type in user dialog box def __init__(self, parent, fileName): """ Dialog box for importing data source with arbitrary column names. """ wx.Dialog.__init__(self, parent, title='Import data from {} file'.format( self.fileType)) self.colNames, self.dataLines = self._parse_header(fileName) sizer1 = wx.BoxSizer(wx.VERTICAL) #sizer2 = wx.BoxSizer(wx.HORIZONTAL) sizer1.Add( wx.StaticText( self, -1, 'Please assign variable names to each column. Some variable names must be present for the program to function correctly' ), 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.GenerateDataGrid(sizer1) sizer2 = wx.BoxSizer(wx.HORIZONTAL) self.stRequiredNotPresent = wx.StaticText( self, -1, 'Required variables not yet defined:\n') sizer2.Add(self.stRequiredNotPresent, 1, wx.ALL, 5) self.stRecommendedNotPresent = wx.StaticText( self, -1, 'Recommended variables not yet defined:\n') sizer2.Add(self.stRecommendedNotPresent, 1, wx.ALL, 5) sizer1.Add(sizer2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, 5) sizer2 = wx.BoxSizer(wx.HORIZONTAL) self.rbLocsInNM = wx.RadioButton(self, -1, "x and y positions are in nm", style=wx.RB_GROUP) self.rbLocsInNM.SetValue(True) sizer1.Add(self.rbLocsInNM, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.EXPAND, 5) self.rbLocsInPixels = wx.RadioButton( self, -1, "x and y positions are in pixels") sizer1.Add(self.rbLocsInPixels, 0, wx.ALIGN_CENTER_VERTICAL | wx.LEFT | wx.EXPAND, 5) self.stPixelSize = wx.StaticText(self, -1, 'Pixel size [nm]:') self.stPixelSize.Disable() sizer2.Add(self.stPixelSize, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.tPixelSize = wx.TextCtrl(self, -1, '1.0') self.tPixelSize.Disable() sizer2.Add(self.tPixelSize, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) sizer1.Add(sizer2, 0, wx.ALIGN_CENTER_VERTICAL | wx.ALL | wx.EXPAND, 5) self.rbLocsInPixels.Bind(wx.EVT_RADIOBUTTON, self.on_toggle_loc_units) self.rbLocsInNM.Bind(wx.EVT_RADIOBUTTON, self.on_toggle_loc_units) btSizer = wx.StdDialogButtonSizer() self.btnOK = wx.Button(self, wx.ID_OK) self.btnOK.SetDefault() self.btnOK.Enable(False) btSizer.AddButton(self.btnOK) btn = wx.Button(self, wx.ID_CANCEL) btSizer.AddButton(btn) btSizer.Realize() sizer1.Add(btSizer, 0, wx.ALIGN_RIGHT | wx.ALIGN_CENTER_VERTICAL | wx.ALL, 5) self.CheckColNames() self.SetSizer(sizer1) sizer1.Fit(self) def on_toggle_loc_units(self, e): #print('rbLocInPix:' + repr(self.rbLocsInPixels.GetValue())) pix = self.rbLocsInPixels.GetValue() self.tPixelSize.Enable(pix) self.stPixelSize.Enable(pix) if not pix: # reset pixel size to 1 self.tPixelSize.SetValue('1.0') def _parse_header(self, file): raise NotImplementedError('Implemented in a derived class.') def CheckColNames(self): reqNotDef = [ var for var in self.requiredVariables.keys() if not var in self.colNames ] if len(reqNotDef) > 0: self.btnOK.Enable(False) sreq = 'Required variables not yet defined:\n' for k in reqNotDef: sreq += '\n\t%s\t-\t%s' % (k, self.requiredVariables[k]) self.stRequiredNotPresent.SetForegroundColour(wx.RED) else: self.btnOK.Enable(True) sreq = 'All required variables are defined\n' self.stRequiredNotPresent.SetForegroundColour(wx.GREEN) self.stRequiredNotPresent.SetLabel(sreq) recNotDef = [ var for var in self.recommendedVariables.keys() if not var in self.colNames ] if len(recNotDef) > 0: sreq = 'Recomended variables not yet defined:\n' for k in recNotDef: sreq += '\n\t%s\t-\t%s' % (k, self.recommendedVariables[k]) self.stRecommendedNotPresent.SetForegroundColour( wx.Colour(200, 150, 0)) else: sreq = 'All recommended variables are defined\n' self.stRecommendedNotPresent.SetForegroundColour(wx.GREEN) self.stRecommendedNotPresent.SetLabel(sreq) def GenerateDataGrid(self, sizer): vsizer = wx.StaticBoxSizer( wx.StaticBox(self, -1, 'Column names and preview:')) self.scrollW = ScrolledPanel(self, -1, size=(800, 150)) self.comboIDs = [] self.combos = [] fgSizer = wx.FlexGridSizer(1 + len(self.dataLines), len(self.colNames), 4, 4) for cn in self.colNames: id = wx.NewId() self.comboIDs.append(id) cb = wx.ComboBox(self.scrollW, id, size=(120, -1), choices=[cn] + list(self.requiredVariables.keys()) + list(self.recommendedVariables.keys()) + list(self.niceVariables.keys())) self.combos.append(cb) cb.SetSelection(0) cb.Bind(wx.EVT_COMBOBOX, self.OnColNameChange) cb.Bind(wx.EVT_TEXT, self.OnColNameChange) fgSizer.Add(cb) for dl in self.dataLines: for de in dl: fgSizer.Add(wx.StaticText(self.scrollW, -1, de)) self.scrollW.SetSizer(fgSizer) self.scrollW.SetAutoLayout(True) self.scrollW.SetupScrolling() vsizer.Add(self.scrollW, 0, wx.EXPAND | wx.ALL, 5) sizer.Add(vsizer, 0, wx.EXPAND | wx.ALL, 5) def OnColNameChange(self, event): colNum = self.comboIDs.index(event.GetId()) self.colNames[colNum] = self.combos[colNum].GetValue() self.CheckColNames() def GetFieldNames(self): return self.colNames def GetNumberComments(self): return self.numCommentLines def GetPixelSize(self): return float(self.tPixelSize.GetValue())