我们从Python开源项目中,提取了以下43个代码示例,用于说明如何使用wx.GetApp()。
def inputhook_wx1(): """Run the wx event loop by processing pending events only. This approach seems to work, but its performance is not great as it relies on having PyOS_InputHook called regularly. """ try: app = wx.GetApp() if app is not None: assert wx.Thread_IsMain() # Make a temporary event loop and process system events until # there are no more waiting, then allow idle events (which # will also deal with pending or posted wx events.) evtloop = wx.EventLoop() ea = wx.EventLoopActivator(evtloop) while evtloop.Pending(): evtloop.Dispatch() app.ProcessIdle() del ea except KeyboardInterrupt: pass return 0
def inputhook_wx2(): """Run the wx event loop, polling for stdin. This version runs the wx eventloop for an undetermined amount of time, during which it periodically checks to see if anything is ready on stdin. If anything is ready on stdin, the event loop exits. The argument to elr.Run controls how often the event loop looks at stdin. This determines the responsiveness at the keyboard. A setting of 1000 enables a user to type at most 1 char per second. I have found that a setting of 10 gives good keyboard response. We can shorten it further, but eventually performance would suffer from calling select/kbhit too often. """ try: app = wx.GetApp() if app is not None: assert wx.Thread_IsMain() elr = EventLoopRunner() # As this time is made shorter, keyboard response improves, but idle # CPU load goes up. 10 ms seems like a good compromise. elr.Run(time=10) # CHANGE time here to control polling interval except KeyboardInterrupt: pass return 0
def inputhook_wx1(): """Run the wx event loop by processing pending events only. This approach seems to work, but its performance is not great as it relies on having PyOS_InputHook called regularly. """ try: app = wx.GetApp() # @UndefinedVariable if app is not None: assert wx.Thread_IsMain() # @UndefinedVariable # Make a temporary event loop and process system events until # there are no more waiting, then allow idle events (which # will also deal with pending or posted wx events.) evtloop = wx.EventLoop() # @UndefinedVariable ea = wx.EventLoopActivator(evtloop) # @UndefinedVariable while evtloop.Pending(): evtloop.Dispatch() app.ProcessIdle() del ea except KeyboardInterrupt: pass return 0
def inputhook_wx2(): """Run the wx event loop, polling for stdin. This version runs the wx eventloop for an undetermined amount of time, during which it periodically checks to see if anything is ready on stdin. If anything is ready on stdin, the event loop exits. The argument to elr.Run controls how often the event loop looks at stdin. This determines the responsiveness at the keyboard. A setting of 1000 enables a user to type at most 1 char per second. I have found that a setting of 10 gives good keyboard response. We can shorten it further, but eventually performance would suffer from calling select/kbhit too often. """ try: app = wx.GetApp() # @UndefinedVariable if app is not None: assert wx.Thread_IsMain() # @UndefinedVariable elr = EventLoopRunner() # As this time is made shorter, keyboard response improves, but idle # CPU load goes up. 10 ms seems like a good compromise. elr.Run(time=10) # CHANGE time here to control polling interval except KeyboardInterrupt: pass return 0
def MyExceptionHook(etype, value, trace): """ Handler for all unhandled exceptions. :param `etype`: the exception type (`SyntaxError`, `ZeroDivisionError`, etc...); :type `etype`: `Exception` :param string `value`: the exception error message; :param string `trace`: the traceback header, if any (otherwise, it prints the standard Python header: ``Traceback (most recent call last)``. """ frame = wx.GetApp().GetTopWindow() tmp = traceback.format_exception(etype, value, trace) exception = "".join(tmp) dlg = ExceptionDialog(exception) dlg.ShowModal() dlg.Destroy()
def insureWxApp(): """Create an instance of PySimpleApp if there is no app already. This is required by wxPython before creating any GUI objects. """ global _wxApp _wxApp = wx.GetApp() if not _wxApp: _wxApp = wx.PySimpleApp() return _wxApp
def __init__(self): ChatFrameGui.__init__(self, None, -1, 'Chat') self._assignEvents() self.server = ChatServer(wx.GetApp(), self.onServerStarted, self.onServerFailed, self.onLine, self.onMsg) self.client = ChatClient()
def send_message(message_id, *args, **kwargs): app = wx.GetApp() if app: wx.CallAfter(pub.sendMessage, message_id, *args, **kwargs) else: pub.sendMessage(message_id, *args, **kwargs)
def get_app_wx(*args, **kwargs): """Create a new wx app or return an exiting one.""" import wx app = wx.GetApp() if app is None: if 'redirect' not in kwargs: kwargs['redirect'] = False app = wx.PySimpleApp(*args, **kwargs) return app
def inputhook_wx2(context): """Run the wx event loop, polling for stdin. This version runs the wx eventloop for an undetermined amount of time, during which it periodically checks to see if anything is ready on stdin. If anything is ready on stdin, the event loop exits. The argument to elr.Run controls how often the event loop looks at stdin. This determines the responsiveness at the keyboard. A setting of 1000 enables a user to type at most 1 char per second. I have found that a setting of 10 gives good keyboard response. We can shorten it further, but eventually performance would suffer from calling select/kbhit too often. """ try: app = wx.GetApp() if app is not None: assert wx.Thread_IsMain() elr = EventLoopRunner() # As this time is made shorter, keyboard response improves, but idle # CPU load goes up. 10 ms seems like a good compromise. elr.Run(time=10, # CHANGE time here to control polling interval input_is_ready=context.input_is_ready) except KeyboardInterrupt: pass return 0
def enable_wx(self, app=None): """Enable event loop integration with wxPython. Parameters ---------- app : WX Application, optional. Running application to use. If not given, we probe WX for an existing application object, and create a new one if none is found. Notes ----- This methods sets the ``PyOS_InputHook`` for wxPython, which allows the wxPython to integrate with terminal based applications like IPython. If ``app`` is not given we probe for an existing one, and return it if found. If no existing app is found, we create an :class:`wx.App` as follows:: import wx app = wx.App(redirect=False, clearSigInt=False) """ import wx from distutils.version import LooseVersion as V wx_version = V(wx.__version__).version # @UndefinedVariable if wx_version < [2, 8]: raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__) # @UndefinedVariable from pydev_ipython.inputhookwx import inputhook_wx self.set_inputhook(inputhook_wx) self._current_gui = GUI_WX if app is None: app = wx.GetApp() # @UndefinedVariable if app is None: app = wx.App(redirect=False, clearSigInt=False) # @UndefinedVariable app._in_event_loop = True self._apps[GUI_WX] = app return app
def wrap_exceptions(func): """Wraps a function with an "exception hook" for threads. Args: func (function): The function to wrap. Returns: function: The wrapped function """ @wraps(func) def wrapper(*args, **kwargs): # args[0] = when wrapping a class method. (IT BETTER BE. WHYDOISUCKATPROGRAMMINGOHGOD) # This should really only be used on threads (main thread has a sys.excepthook) try: return func(*args, **kwargs) except (SystemExit, KeyboardInterrupt): raise except Exception: if isinstance(args[0], wx.TopLevelWindow): parent = args[0] elif hasattr(args[0], "parent") and isinstance(args[0].parent, wx.TopLevelWindow): parent = args[0].parent else: parent = wx.GetApp().GetTopWindow() error_message = ''.join(traceback.format_exc()) error_dialog = wx.MessageDialog(parent=parent, message="An error has occured\n\n" + error_message, caption="Error!", style=wx.OK | wx.ICON_ERROR) error_dialog.RequestUserAttention() error_dialog.ShowModal() error_dialog.Destroy() logger.critical(error_message) raise return wrapper
def OnTaskBarWXInspector(self, evt): # Activate the widget inspection tool from wx.lib.inspection import InspectionTool if not InspectionTool().initialized: InspectionTool().Init(**self._LiveShellLocals()) wnd = wx.GetApp() InspectionTool().Show(wnd, True)
def OnTaskBarQuit(self, evt): if wx.Platform == '__WXMSW__': Thread(target=self.pyroserver.Quit).start() self.RemoveIcon() wx.CallAfter(wx.GetApp().ExitMainLoop)
def OnTBAuto(self, event): if self.cam is None: return if self.running: wx.MessageBox('Please pause acquisition first!', 'Acquisition in progress!', wx.OK | wx.ICON_INFORMATION) return msg = "Setting automatic exposure time / gain.. please wait.." busyDlg = wx.BusyInfo(msg) self.tb.Enable(False) wx.GetApp().Yield() _, ovexp = self.readCamera() while not ovexp: if self.camSupportsExp() and self.exp < self.expmax: self.OnRTBExpInc() elif self.camSupportsGain() and self.gain < self.gainmax: self.OnRTBGainInc() else: break _, ovexp = self.readCamera() wx.GetApp().Yield() while ovexp: if self.camSupportsGain() and self.gain > self.gainmin: self.OnRTBGainDec() elif self.camSupportsExp() and self.exp > self.expmin: self.OnRTBExpDec() else: break _, ovexp = self.readCamera() wx.GetApp().Yield() busyDlg = None self.tb.Enable(True)
def OnClose(self, event): print("[wxpython.py] OnClose called") if not self.browser: # May already be closing, may be called multiple times on Mac return if MAC: # On Mac things work differently, other steps are required self.browser.CloseBrowser() self.clear_browser_references() self.Destroy() global g_count_windows g_count_windows -= 1 if g_count_windows == 0: cef.Shutdown() wx.GetApp().ExitMainLoop() # Call _exit otherwise app exits with code 255 (Issue #162). # noinspection PyProtectedMember os._exit(0) else: # Calling browser.CloseBrowser() and/or self.Destroy() # in OnClose may cause app crash on some paltforms in # some use cases, details in Issue #107. self.browser.ParentWindowWillClose() event.Skip() self.clear_browser_references()
def __init__(self): caller_info = app_utils.get_caller_info() owner = caller_info[1][1] # TODO: Armengue feito para as funcoes dos menus.. tentar corrigir isso if not owner: owner = wx.GetApp() try: owner_name = owner.uid except AttributeError: owner_name = owner.__class__.__name__ msg = 'A new instance of ' + self.__class__.__name__ + \ ' was solicited by {}'.format(owner_name) log.debug(msg) self._ownerref = weakref.ref(owner)
def enable(self, app=None): """DEPRECATED since IPython 5.0 Enable event loop integration with wxPython. Parameters ---------- app : WX Application, optional. Running application to use. If not given, we probe WX for an existing application object, and create a new one if none is found. Notes ----- This methods sets the ``PyOS_InputHook`` for wxPython, which allows the wxPython to integrate with terminal based applications like IPython. If ``app`` is not given we probe for an existing one, and return it if found. If no existing app is found, we create an :class:`wx.App` as follows:: import wx app = wx.App(redirect=False, clearSigInt=False) """ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.", DeprecationWarning, stacklevel=2) import wx wx_version = V(wx.__version__).version if wx_version < [2, 8]: raise ValueError("requires wxPython >= 2.8, but you have %s" % wx.__version__) from IPython.lib.inputhookwx import inputhook_wx self.manager.set_inputhook(inputhook_wx) if _use_appnope(): from appnope import nope nope() import wx if app is None: app = wx.GetApp() if app is None: app = wx.App(redirect=False, clearSigInt=False) return app
def inputhook_wx3(): """Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: app = wx.GetApp() if app is not None: assert wx.Thread_IsMain() # The import of wx on Linux sets the handler for signal.SIGINT # to 0. This is a bug in wx or gtk. We fix by just setting it # back to the Python default. if not callable(signal.getsignal(signal.SIGINT)): signal.signal(signal.SIGINT, signal.default_int_handler) evtloop = wx.EventLoop() ea = wx.EventLoopActivator(evtloop) t = clock() while not stdin_ready(): while evtloop.Pending(): t = clock() evtloop.Dispatch() app.ProcessIdle() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) del ea except KeyboardInterrupt: pass return 0
def inputhook_wx3(context): """Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: app = wx.GetApp() if app is not None: assert wx.Thread_IsMain() # The import of wx on Linux sets the handler for signal.SIGINT # to 0. This is a bug in wx or gtk. We fix by just setting it # back to the Python default. if not callable(signal.getsignal(signal.SIGINT)): signal.signal(signal.SIGINT, signal.default_int_handler) evtloop = wx.EventLoop() ea = wx.EventLoopActivator(evtloop) t = clock() while not context.input_is_ready(): while evtloop.Pending(): t = clock() evtloop.Dispatch() app.ProcessIdle() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) del ea except KeyboardInterrupt: pass return 0
def inputhook_wx3(): """Run the wx event loop by processing pending events only. This is like inputhook_wx1, but it keeps processing pending events until stdin is ready. After processing all pending events, a call to time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%. This sleep time should be tuned though for best performance. """ # We need to protect against a user pressing Control-C when IPython is # idle and this is running. We trap KeyboardInterrupt and pass. try: app = wx.GetApp() # @UndefinedVariable if app is not None: assert wx.Thread_IsMain() # @UndefinedVariable # The import of wx on Linux sets the handler for signal.SIGINT # to 0. This is a bug in wx or gtk. We fix by just setting it # back to the Python default. if not callable(signal.getsignal(signal.SIGINT)): signal.signal(signal.SIGINT, signal.default_int_handler) evtloop = wx.EventLoop() # @UndefinedVariable ea = wx.EventLoopActivator(evtloop) # @UndefinedVariable t = clock() while not stdin_ready(): while evtloop.Pending(): t = clock() evtloop.Dispatch() app.ProcessIdle() # We need to sleep at this point to keep the idle CPU load # low. However, if sleep to long, GUI response is poor. As # a compromise, we watch how often GUI events are being processed # and switch between a short and long sleep time. Here are some # stats useful in helping to tune this. # time CPU load # 0.001 13% # 0.005 3% # 0.01 1.5% # 0.05 0.5% used_time = clock() - t if used_time > 10.0: # print 'Sleep for 1 s' # dbg time.sleep(1.0) elif used_time > 0.1: # Few GUI events coming in, so we can sleep longer # print 'Sleep for 0.05 s' # dbg time.sleep(0.05) else: # Many GUI events coming in, so sleep only very little time.sleep(0.001) del ea except KeyboardInterrupt: pass return 0
def OnUpdate(self, event=None): # read data from camera # if self.cam is None: # return data, ovexp = self.readCamera() # light level warning if self.levelwasok and ovexp: self.levelwasok = False self.tblightlevel.SetBitmap(self.tblightlevel2BMP) elif not self.levelwasok and not ovexp: self.levelwasok = True self.tblightlevel.SetBitmap(self.tblightlevel1BMP) # dark level subtraction if self.dark is not None: data = data - self.dark # force minimum pixel value to be 1 to prevent NaNs data = np.maximum(np.ones(len(data)), data) # UVVIS or spectrum if self.modeUVVIS and self.reference is not None: data = np.nan_to_num(-np.log10(data / self.reference)) # add to running average if recording if self.recording: if self.data is not None: self.data = (float(self.cAvg) * self.data + data) / float(self.cAvg + 1) self.cAvg = self.cAvg + 1 else: self.data = data.copy() self.cAvg = 1 if self.cAvg >= self.avg: self.ok_to_overwrite = False self.OnTBStart() # recording stops elif self.ok_to_overwrite: self.data = data.copy() # force some kind of x-axis if self.wlAxis is None: self.wlAxis = np.arange(len(self.data)) # overwrite main line in plot self.addLine(self.wlAxis, self.data, id=0) # restart timer if self.running: wx.GetApp().Yield() # process all GUI events to keep the program responsive self.updThread.Start(200, wx.TIMER_ONE_SHOT)