Python wx.CallAfter() Examples

The following are 30 code examples of wx.CallAfter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module wx , or try the search function .
Example #1
Source File: guicontrols.py    From wfuzz with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, parent, frame, interpreter):
        self._frame = frame
        wx.Panel.__init__(self, parent, -1)

        bookStyle = aui.AUI_NB_DEFAULT_STYLE
        bookStyle &= ~(aui.AUI_NB_CLOSE_ON_ACTIVE_TAB)

        self.rawpanel = HttpRawPanel(self, self)
        self.renderpanel = self.create_web_view()

        self.nb = aui.AuiNotebook(self, style=bookStyle)
        self.nb.AddPage(self.rawpanel, "HTML Raw")
        self.nb.AddPage(self.renderpanel, "HTML Render")

        sizer = wx.BoxSizer()
        sizer.Add(self.nb, 1, wx.EXPAND)
        self.SetSizer(sizer)
        wx.CallAfter(self.nb.SendSizeEvent)

        pub.subscribe(self.on_selected_row, "selected_row") 
Example #2
Source File: guiminer.py    From poclbm with GNU General Public License v3.0 6 votes vote down vote up
def request_payout_btcmp(self, balance_auth_token):
        """Request payout from btcmp's server via HTTP POST."""        
        response, data = http_request(
            self.server_config['balance_host'],
            "GET",
            self.server_config["payout_url"] % balance_auth_token,
            use_https=False
        )
        
        if self.is_auth_token_rejected(response):
            data = _("Auth token rejected by server.")
        elif not data:
            data = STR_CONNECTION_ERROR
        else:
            data = _("Withdraw OK")
        wx.CallAfter(self.on_balance_received, data) 
Example #3
Source File: guiminer.py    From poclbm with GNU General Public License v3.0 6 votes vote down vote up
def request_payout_deepbit(self, balance_auth_token):
        """Request payout from deepbit's server via HTTP POST."""
        post_params = dict(id=1,
                           method="request_payout")
        response, data = http_request(
             self.server_config['balance_host'],
             "POST",
             self.server_config['balance_url'] % balance_auth_token,
             json.dumps(post_params),
             {"Content-type": "application/json; charset=utf-8",
              "User-Agent": USER_AGENT}
        )
        if self.is_auth_token_rejected(response):
            data = _("Auth token rejected by server.")
        elif not data:
            data = STR_CONNECTION_ERROR
        else:
            data = _("Withdraw OK")
        wx.CallAfter(self.on_balance_received, data) 
Example #4
Source File: guiminer.py    From poclbm with GNU General Public License v3.0 6 votes vote down vote up
def request_balance_eligius(self):
        """Request our balance from Eligius
        """
        response, data = http_request(
             self.server_config['balance_host'],
             "POST",
             self.server_config['balance_url'] % (self.txt_username.GetValue(),),
        )
        if not data:
            data = STR_CONNECTION_ERROR
        try:
            data = json.loads(data)
            data = data['expected'] / 1e8
        except BaseException as e:
            data = str(e)
        wx.CallAfter(self.on_balance_received, data) 
Example #5
Source File: runsnake.py    From pyFileFixity with MIT License 6 votes vote down vote up
def OnInit(self, profile=None, memoryProfile=None):
        """Initialise the application"""
        wx.Image.AddHandler(self.handler)
        frame = MainFrame( config_parser = load_config())
        frame.Show(True)
        self.SetTopWindow(frame)
        if profile:
            wx.CallAfter(frame.load, *[profile])
        elif sys.argv[1:]:
            if sys.argv[1] == '-m':
                if sys.argv[2:]:
                    wx.CallAfter( frame.load_memory, sys.argv[2] )
                else:
                    log.warn( 'No memory file specified' )
            else:
                wx.CallAfter(frame.load, *sys.argv[1:])
        return True 
Example #6
Source File: core.py    From wafer_map with GNU General Public License v3.0 6 votes vote down vote up
def write(self, text):
        """
        Create the output window if needed and write the string to it.
        If not called in the context of the gui thread then CallAfter is 
        used to do the work there.
        """
        if self.frame is None:
            if not wx.IsMainThread():
                wx.CallAfter(self.CreateOutputWindow, text)
            else:
                self.CreateOutputWindow(text)
        else:
            if not wx.IsMainThread():
                wx.CallAfter(self.text.AppendText, text)
            else:
                self.text.AppendText(text) 
Example #7
Source File: commondialogs.py    From CANFestivino with GNU Lesser General Public License v2.1 5 votes vote down vote up
def OnValuesGridSelectCell(self, event):
        wx.CallAfter(self.RefreshButtons)
        event.Skip() 
Example #8
Source File: integ_autostart.py    From Gooey with MIT License 5 votes vote down vote up
def verifyAutoStart(self, app, buildSpec):
        """
        When the auto_start flag == True Gooey should skip the
        configuration screen
        """
        time.sleep(1)
        try:
            # Gooey should NOT be showing the name/description headers
            # present on the config page
            title = app.TopWindow.header._header.GetLabel()
            subtitle = app.TopWindow.header._subheader.GetLabel()
            self.assertNotEqual(title, buildSpec['program_name'])
            self.assertNotEqual(subtitle, buildSpec['program_description'])

            # Gooey should be showing the console messages straight away
            # without manually starting the program
            title = app.TopWindow.header._header.GetLabel()
            subtitle = app.TopWindow.header._subheader.GetLabel()
            self.assertEqual(title,_("running_title"))
            self.assertEqual(subtitle, _('running_msg'))

            # Wait for Gooey to swap the header to the final screen
            while app.TopWindow.header._header.GetLabel() == _("running_title"):
                time.sleep(.1)

            # verify that we've landed on the success screen
            title = app.TopWindow.header._header.GetLabel()
            subtitle = app.TopWindow.header._subheader.GetLabel()
            self.assertEqual(title, _("finished_title"))
            self.assertEqual(subtitle, _('finished_msg'))


            # and that output was actually written to the console
            self.assertIn("Success", app.TopWindow.console.textbox.GetValue())
        except:
            app.TopWindow.Destroy()
            raise
        else:
            import wx
            wx.CallAfter(app.TopWindow.Destroy)
            return None 
Example #9
Source File: subindextable.py    From CANFestivino with GNU Lesser General Public License v2.1 5 votes vote down vote up
def OnSubindexGridCellChange(self, event):
        if self.Editable:
            index = self.Table.GetCurrentIndex()
            subIndex = event.GetRow()
            col = event.GetCol()
            name = self.Table.GetColLabelValue(col, False)
            value = self.Table.GetValue(subIndex, col, False)
            editor = self.Table.GetEditor(subIndex, col)
            self.Manager.SetCurrentEntry(index, subIndex, value, name, editor)
            self.ParentWindow.RefreshBufferState()
            wx.CallAfter(self.RefreshTable)
        event.Skip() 
Example #10
Source File: ListCtrl.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def OnEraseBackground(self, event=None):
        nsp = self.GetScrollPos(wx.VERTICAL)
        if self._last_scrollpos != nsp:
            self._last_scrollpos = nsp
            # should only refresh visible items, hmm
            wx.CallAfter(self.Refresh)
        dc = wx.ClientDC(self)
        # erase the section of the background which is not covered by the
        # items or the selected column highlighting
        dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
        f = self.GetRect()
        r = wx.Region(0, 0, f.width, f.height)
        x = self.GetVisibleViewRect()
        offset = self._get_origin_offset(include_header=True)
        x.Offset(offset)
        r.SubtractRect(x)
        if '__WXMSW__' in wx.PlatformInfo:
            c = self.GetColumnRect(self.enabled_columns.index(self.selected_column))
            r.SubtractRect(c)
        dc.SetClippingRegionAsRegion(r)
        dc.Clear()

        if '__WXMSW__' in wx.PlatformInfo:
            # draw the selected column highlighting under the items
            dc.DestroyClippingRegion()
            r = wx.Region(0, 0, f.width, f.height)
            r.SubtractRect(x)
            dc.SetClippingRegionAsRegion(r)
            dc.SetPen(wx.TRANSPARENT_PEN)
            hc = wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW)
            r = highlight_color(hc.Red())
            g = highlight_color(hc.Green())
            b = highlight_color(hc.Blue())
            hc.Set(r, g, b)
            dc.SetBrush(wx.Brush(hc))
            dc.DrawRectangle(c.x, c.y, c.width, c.height) 
Example #11
Source File: OpenDialog.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def OnComboBox(self, event):
        wx.CallAfter(self._OnChange, event.GetString()) 
Example #12
Source File: viewer.py    From GraphLayout with MIT License 5 votes vote down vote up
def __init__(self, parent):
        super(View, self).__init__(parent)
        self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.Bind(wx.EVT_SIZE, self.on_size)
        self.Bind(wx.EVT_PAINT, self.on_paint)
        self.Bind(wx.EVT_CHAR_HOOK, self.on_char)
        self.index = -1
        self.weights = {}
        self.model = None
        self.bitmap = None
        wx.CallAfter(self.next) 
Example #13
Source File: harness.py    From Gooey with MIT License 5 votes vote down vote up
def instrumentGooey(parser, **kwargs):
    """
    Context manager used during testing for setup/tear down of the
    WX infrastructure during subTests.
    """
    buildspec = create_from_parser(parser, "", **merge(defaults, kwargs))
    app, gooey = application.build_app(buildspec)
    try:
        yield (app, gooey)
    finally:
        wx.CallAfter(app.ExitMainLoop)
        gooey.Destroy()
        app.Destroy() 
Example #14
Source File: commondialogs.py    From CANFestivino with GNU Lesser General Public License v2.1 5 votes vote down vote up
def OnValuesGridCellChange(self, event):
        row, col = event.GetRow(), event.GetCol()
        colname = self.Table.GetColLabelValue(col)
        value = self.Table.GetValue(row, col)
        try:
            self.Values[row][colname] = int(value, 16)
        except:
            message = wx.MessageDialog(self, _("\"%s\" is not a valid value!")%value, _("Error"), wx.OK|wx.ICON_ERROR)
            message.ShowModal()
            message.Destroy()
        wx.CallAfter(self.RefreshValues)
        event.Skip() 
Example #15
Source File: networkedit.py    From CANFestivino with GNU Lesser General Public License v2.1 5 votes vote down vote up
def AddExceptHook(path, app_version='[No version]'):#, ignored_exceptions=[]):
    
    def handle_exception(e_type, e_value, e_traceback):
        traceback.print_exception(e_type, e_value, e_traceback) # this is very helpful when there's an exception in the rest of this func
        last_tb = get_last_traceback(e_traceback)
        ex = (last_tb.tb_frame.f_code.co_filename, last_tb.tb_frame.f_lineno)
        if str(e_value).startswith("!!!"):
            Display_Error_Dialog(e_value)
        elif ex not in ignored_exceptions:
            ignored_exceptions.append(ex)
            result = Display_Exception_Dialog(e_type,e_value,e_traceback)
            if result:
                info = {
                    'app-title' : wx.GetApp().GetAppName(), # app_title
                    'app-version' : app_version,
                    'wx-version' : wx.VERSION_STRING,
                    'wx-platform' : wx.Platform,
                    'python-version' : platform.python_version(), #sys.version.split()[0],
                    'platform' : platform.platform(),
                    'e-type' : e_type,
                    'e-value' : e_value,
                    'date' : time.ctime(),
                    'cwd' : os.getcwd(),
                    }
                if e_traceback:
                    info['traceback'] = ''.join(traceback.format_tb(e_traceback)) + '%s: %s' % (e_type, e_value)
                    last_tb = get_last_traceback(e_traceback)
                    exception_locals = last_tb.tb_frame.f_locals # the locals at the level of the stack trace where the exception actually occurred
                    info['locals'] = format_namespace(exception_locals)
                    if 'self' in exception_locals:
                        info['self'] = format_namespace(exception_locals['self'].__dict__)
                
                output = open(path+os.sep+"bug_report_"+info['date'].replace(':','-').replace(' ','_')+".txt",'w')
                lst = info.keys()
                lst.sort()
                for a in lst:
                    output.write(a+":\n"+str(info[a])+"\n\n")

    #sys.excepthook = lambda *args: wx.CallAfter(handle_exception, *args)
    sys.excepthook = handle_exception 
Example #16
Source File: objdictedit.py    From CANFestivino with GNU Lesser General Public License v2.1 5 votes vote down vote up
def AddExceptHook(path, app_version='[No version]'):#, ignored_exceptions=[]):
    
    def handle_exception(e_type, e_value, e_traceback):
        traceback.print_exception(e_type, e_value, e_traceback) # this is very helpful when there's an exception in the rest of this func
        last_tb = get_last_traceback(e_traceback)
        ex = (last_tb.tb_frame.f_code.co_filename, last_tb.tb_frame.f_lineno)
        if str(e_value).startswith("!!!"):
            Display_Error_Dialog(e_value)
        elif ex not in ignored_exceptions:
            ignored_exceptions.append(ex)
            result = Display_Exception_Dialog(e_type,e_value,e_traceback)
            if result:
                info = {
                    'app-title' : wx.GetApp().GetAppName(), # app_title
                    'app-version' : app_version,
                    'wx-version' : wx.VERSION_STRING,
                    'wx-platform' : wx.Platform,
                    'python-version' : platform.python_version(), #sys.version.split()[0],
                    'platform' : platform.platform(),
                    'e-type' : e_type,
                    'e-value' : e_value,
                    'date' : time.ctime(),
                    'cwd' : os.getcwd(),
                    }
                if e_traceback:
                    info['traceback'] = ''.join(traceback.format_tb(e_traceback)) + '%s: %s' % (e_type, e_value)
                    last_tb = get_last_traceback(e_traceback)
                    exception_locals = last_tb.tb_frame.f_locals # the locals at the level of the stack trace where the exception actually occurred
                    info['locals'] = format_namespace(exception_locals)
                    if 'self' in exception_locals:
                        info['self'] = format_namespace(exception_locals['self'].__dict__)
                
                output = open(path+os.sep+"bug_report_"+info['date'].replace(':','-').replace(' ','_')+".txt",'w')
                lst = info.keys()
                lst.sort()
                for a in lst:
                    output.write(a+":\n"+str(info[a])+"\n\n")

    #sys.excepthook = lambda *args: wx.CallAfter(handle_exception, *args)
    sys.excepthook = handle_exception 
Example #17
Source File: objdictedit.py    From CANFestivino with GNU Lesser General Public License v2.1 5 votes vote down vote up
def OnFileSelectedChanged(self, event):
        if not self.Closing:
            selected = event.GetSelection()
            # At init selected = -1
            if selected >= 0:
                window = self.FileOpened.GetPage(selected)
                if window:
                    self.Manager.ChangeCurrentNode(window.GetIndex())
                    wx.CallAfter(self.RefreshBufferState)
                    self.RefreshStatusBar()
                    self.RefreshProfileMenu()
        event.Skip() 
Example #18
Source File: integ_validations.py    From Gooey with MIT License 5 votes vote down vote up
def verifyValidators(self, app, buildSpec):
        time.sleep(1)
        try:
            app.TopWindow.onStart()
            title = app.TopWindow.header._header.GetLabel()
            subtitle = app.TopWindow.header._subheader.GetLabel()
            self.assertNotEqual(title, buildSpec['program_name'])
            self.assertNotEqual(subtitle, buildSpec['program_description'])
        except:
            app.TopWindow.Destroy()
            raise
        else:
            import wx
            wx.CallAfter(app.TopWindow.Destroy)
            return None 
Example #19
Source File: integ_widget_demo.py    From Gooey with MIT License 5 votes vote down vote up
def gooeySanityTest(self, app, buildSpec):
        time.sleep(1)
        try:
            # Check out header is present and showing data
            title = app.TopWindow.header._header.GetLabel()
            subtitle = app.TopWindow.header._subheader.GetLabel()
            self.assertEqual(title, buildSpec['program_name'])
            self.assertEqual(subtitle, buildSpec['program_description'])

            # switch to the run screen
            app.TopWindow.onStart()

            # Should find the expected test in the header
            title = app.TopWindow.header._header.GetLabel()
            subtitle = app.TopWindow.header._subheader.GetLabel()
            self.assertEqual(title,_("running_title"))
            self.assertEqual(subtitle, _('running_msg'))

            # Wait for Gooey to swap the header to the final screen
            while app.TopWindow.header._header.GetLabel() == _("running_title"):
                time.sleep(.1)

            # verify that we've landed on the success screen
            title = app.TopWindow.header._header.GetLabel()
            subtitle = app.TopWindow.header._subheader.GetLabel()
            self.assertEqual(title, _("finished_title"))
            self.assertEqual(subtitle, _('finished_msg'))

            # and that output was actually written to the console
            self.assertIn("Success", app.TopWindow.console.textbox.GetValue())
            time.sleep(1)
        except:
            app.TopWindow.Destroy()
            raise
        else:
            wx.CallAfter(app.TopWindow.Destroy)
            return None 
Example #20
Source File: dfgui.py    From PandasDataFrameGUI with MIT License 5 votes vote down vote up
def on_tab_change(self, event):
        self.page2.list_box.SetFocus()
        page_to_select = event.GetSelection()
        wx.CallAfter(self.fix_focus, page_to_select)
        event.Skip(True) 
Example #21
Source File: dfgui.py    From PandasDataFrameGUI with MIT License 5 votes vote down vote up
def on_left_down(self, event):
        if self.HitTest(event.GetPosition()) != wx.NOT_FOUND:
            index = self.HitTest(event.GetPosition())
            self.selected_items[index] = not self.selected_items[index]
            # doesn't really work to update selection direclty (focus issues)
            # instead we wait for the EVT_LISTBOX event and fix the selection
            # there...
            # self.update_selection()
            # TODO: we could probably use wx.CallAfter
        event.Skip() 
Example #22
Source File: elecsus_gui.py    From ElecSus with Apache License 2.0 5 votes vote down vote up
def run(self):
		""" Action to run when .start() method is called """
		while self.mainwin.already_fitting:
			for i in range(100):
				if not self.mainwin.already_fitting: break
				#print i,' ',
				#wx.CallAfter(self.pb.SetValue,i)
				wx.CallAfter(self.pb.Update,i)
				time.sleep(0.1)
		print('Quitting progress bar update') 
Example #23
Source File: elecsus_gui.py    From ElecSus with Apache License 2.0 5 votes vote down vote up
def __init__(self,parent,mainwin,title,plottype,pos):
		wx.Dialog.__init__(self,parent,wx.ID_ANY,title,size=(400,600),pos=pos)

		self.mainwin = mainwin
		self.plottype = plottype

		win = wx.Panel(self) #,wx.ID_ANY,pos=(0,0),size=(180,200),style=0)

		self.selection = wx.CheckListBox(win, wx.ID_ANY, choices = OutputPlotTypes, size=(120,-1))#,pos=(0,0))
		#self.win.Bind(wx.EVT_CHECKLISTBOX, self.OnTicked, self.selection)
		self.selection.Bind(wx.EVT_CHECKLISTBOX, self.OnTicked)
		
		if plottype == 'Theory':
			display_curves = self.mainwin.display_theory_curves
		else:
			display_curves = self.mainwin.display_expt_curves

		checked_items = []
		for i in range(len(display_curves)):
			if display_curves[i]:
				checked_items.append(i)

		self.selection.SetChecked(checked_items)
		#self.okbtn = wx.Button(self.win,wx.ID_OK,size=(120,BtnSize))
		#self.Bind(wx.EVT_BUTTON, self.OnOK, self.okbtn)

		self.SetSize(self.selection.GetSize()+(50,50))
		self.SetMinSize(self.selection.GetSize()+(50,50))
		
		popup_sizer = wx.BoxSizer(wx.VERTICAL)
		popup_sizer.Add(self.selection,0,wx.EXPAND|wx.ALL, 7)
		#popup_sizer.Add((-1,5),1,wx.EXPAND)
		#popup_sizer.Add(self.okbtn,0,wx.EXPAND)

		#sz = popup_sizer.GetBestSize()
		#self.win.SetSize((sz.width+20, sz.height+20))
		
		self.SetSizer(popup_sizer)
		wx.CallAfter(self.Refresh) 
Example #24
Source File: runsnake.py    From pyFileFixity with MIT License 5 votes vote down vote up
def OnInit(self):
        """Initialise the application"""
        wx.Image.AddHandler(self.handler)
        frame = MainFrame( config_parser = load_config())
        frame.Show(True)
        self.SetTopWindow(frame)
        if sys.argv[1:]:
            wx.CallAfter( frame.load_memory, sys.argv[1] )
        else:
            log.warn( 'No memory file specified' )
        return True 
Example #25
Source File: controller.py    From pyFileFixity with MIT License 5 votes vote down vote up
def read_stdout(self, process, callback):
    while True:
      line = process.stdout.readline()
      if not line:
        break
      wx.CallAfter(self.core_gui.PublishConsoleMsg, line)
    wx.CallAfter(callback, process) 
Example #26
Source File: tray.py    From superpaper with MIT License 5 votes vote down vote up
def on_exit(self, event):
        """Exits Superpaper."""
        self.rt_stop()
        wx.CallAfter(self.Destroy)
        self.frame.Close() 
Example #27
Source File: guiminer.py    From poclbm with GNU General Public License v3.0 5 votes vote down vote up
def on_taskbar_close(self, evt):
        wx.CallAfter(self.frame.Close, force=True) 
Example #28
Source File: guiminer.py    From poclbm with GNU General Public License v3.0 5 votes vote down vote up
def write(self, text):
        """Forward logging events to our TextCtrl."""
        wx.CallAfter(self.append_text, text) 
Example #29
Source File: GoSyncController.py    From gosync with GNU General Public License v2.0 5 votes vote down vote up
def OnExit(self, event):
        dial = wx.MessageDialog(None, 'GoSync will stop syncing files until restarted.\nAre you sure to quit?\n',
                                'Question', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION)
        res = dial.ShowModal()
        if res == wx.ID_YES:
            if self.sync_model.IsSyncEnabled() or self.sync_model.IsSyncRunning():
                self.sync_model.StopTheShow()
                self.sb.SetStatusText("Paused", 1)

            wx.CallAfter(self.Destroy) 
Example #30
Source File: MainUI.py    From Model-Playgrounds with MIT License 5 votes vote down vote up
def run(self):
        wx.CallAfter(pub.sendMessage, "report101", message="Prediction process started. \nLoading........") # Sending report to the Text Box
        import InceptionPrediction
        result = InceptionPrediction.run(self.path, self.model_path, self.index_file_path, self.main_ui) # This calls the Inception Prediction Class
        wx.CallAfter(pub.sendMessage, "report101", message=result) # # Sending report to the Text Box