def MainLoop(self, run_func): evtloop = wx.GUIEventLoop() old = wx.EventLoop.GetActive() wx.EventLoop.SetActive(evtloop) while self.keepGoing: run_func() while not q.empty(): next_job = q.get() DoJob(Bot, next_job) while evtloop.Pending(): evtloop.Dispatch() time.sleep(0.10) evtloop.ProcessIdle() wx.EventLoop.SetActive(old)
async def MainLoop(self): """Asynchronous version of combined asyncio and wxPython event loops.""" # inspired by https://github.com/wxWidgets/Phoenix/blob/master/samples/mainloop/mainloop.py evtloop = wx.GUIEventLoop() with wx.EventLoopActivator(evtloop): while any(self.top_windows) and not self.exiting: if IS_MAC: # evtloop.Pending() just returns True on MacOs evtloop.DispatchTimeout(0) else: while evtloop.Pending(): evtloop.Dispatch() # We don't stop more than necessary, doing otherwise will create latency await asyncio.sleep(0.0000000000001) self.ProcessPendingEvents() evtloop.ProcessIdle() # At this point we just exit the main loop self.ExitMainLoop()
async def MainLoop(self): print("MainLoop") # inspired by https://github.com/wxWidgets/Phoenix/blob/master/samples/mainloop/mainloop.py evtloop = wx.GUIEventLoop() with wx.EventLoopActivator(evtloop): while not self.exiting: if IS_MAC: # evtloop.Pending() just returns True on MacOs evtloop.DispatchTimeout(0) print("x", end='') else: while evtloop.Pending(): evtloop.Dispatch() print("y", end='') await asyncio.sleep(0.005) print("z", end='') # self.DeletePendingEvents() # experiment self.ProcessPendingEvents() evtloop.ProcessIdle() print(random.randint(0, 100), end=' ') sys.stdout.flush()
def __init__(self, parent): wx.Frame.__init__(self, parent) from wx.lib.pdfviewer import pdfViewer, pdfButtonPanel self.Maximize(True) self.parent = parent self.Bind(wx.EVT_CLOSE, self.OnCloseFrm) hsizer = wx.BoxSizer(wx.HORIZONTAL) vsizer = wx.BoxSizer(wx.VERTICAL) self.buttonpanel = pdfButtonPanel(self, wx.NewId(), wx.DefaultPosition, wx.DefaultSize, 0) vsizer.Add(self.buttonpanel, 0, wx.GROW | wx.LEFT | wx.RIGHT | wx.TOP, 5) self.viewer = pdfViewer(self, wx.NewId(), wx.DefaultPosition, wx.DefaultSize, wx.HSCROLL | wx.VSCROLL | wx.SUNKEN_BORDER) vsizer.Add(self.viewer, 1, wx.GROW | wx.LEFT | wx.RIGHT | wx.BOTTOM, 5) loadbutton = wx.Button(self, wx.NewId(), "Load PDF file", wx.DefaultPosition, wx.DefaultSize, 0) loadbutton.SetForegroundColour((255, 0, 0)) vsizer.Add(loadbutton, 0, wx.ALIGN_CENTER | wx.ALL, 5) hsizer.Add(vsizer, 1, wx.GROW | wx.ALL, 5) self.SetSizer(hsizer) self.SetAutoLayout(True) # introduce buttonpanel and viewer to each other self.buttonpanel.viewer = self.viewer self.viewer.buttonpanel = self.buttonpanel self.Bind(wx.EVT_BUTTON, self.OnLoadButton, loadbutton) self.CenterOnParent() self.GetParent().Enable(False) self.Show(True) self.__eventLoop = wx.GUIEventLoop() self.__eventLoop.Run()
def __init__(self): BaseApplicationBackend.__init__(self) self._event_loop = wx.GUIEventLoop() wx.EventLoop.SetActive(self._event_loop)
def MainLoop(self): self.My_EventLoop = wx.GUIEventLoop() old = wx.EventLoop.GetActive () wx.EventLoop.SetActive ( self.My_EventLoop ) #*************************** # Main Loop #*************************** process_this_frame = True PG.App_Running = True Previous_Time = time.time() #Device context while PG.App_Running: #time.sleep ( 0.01) ret, frame = PG.cam.read() frame = cv.flip(frame, 0) #ret2, data = PG.cam2.read() data = q.get(True, 500) data = cv.flip(data, 0) data2 = data data = cv.resize(data[:,:], (640, 480)) min_c = ctok(7) max_c = ctok(20) data[0][0] = min_c data[-1][-1] = max_c frame2 = cv.LUT(raw_to_8bit(data2), generate_colour_map()) frame2 = cv.resize(frame2[:,:], (640, 480)) PG.data = data #cv.imshow("camera", cv.resize(frame2, (640, 480))) frame = cv.cvtColor(frame,cv.COLOR_BGR2RGB) frame2 = cv.cvtColor(frame2,cv.COLOR_BGR2RGB) #view on interface try: #frame = Detect_masked_face(frame) face_recognition_name(frame,frame2) except Exception as e: print(e) PG.view = True PG.Main_Frame.m_panel_video.Refresh() PG.Main_Frame.m_panel_video_thermography.Refresh() process_this_frame = not process_this_frame #bug in macos while self.My_EventLoop.Pending(): self.My_EventLoop.Dispatch() #self.ProcessIdle() self.My_EventLoop.ProcessIdle() # normally 50 fps sec = time.time() - Previous_Time fps = 1 / (sec) str_fps = 'FPS: %2.3f' % fps str_fps = str_fps +" IP: " + PG.IP_addr PG.Main_Frame.SetStatusText(str_fps,0) Previous_Time = time.time() PG.cam.release() libuvc.uvc_stop_streaming(PG.devh) libuvc.uvc_unref_device(PG.dev) libuvc.uvc_exit(PG.ctx)
def __init__(self, parent=None, id=-1, title="", message="", agwStyle=wx.PD_APP_MODAL|wx.PD_AUTO_HIDE): """ Default class constructor. :param `parent`: parent window; :param `id`: window identifier. A value of -1 indicates a default value; :param `title`: dialog title to show in titlebar; :param `message`: message displayed above the progress bar; :param `style`: the dialog style. This can be a combination of the following bits: =================== =========== ================================================== Window Styles Hex Value Description =================== =========== ================================================== ``PD_CAN_ABORT`` 0x1 This flag tells the dialog that it should have a ``Cancel`` button which the user may press. If this happens, the next call to `UpdatePulse` will return ``False``. ``PD_APP_MODAL`` 0x2 Make the progress dialog modal. If this flag is not given, it is only 'locally' modal - that is the input to the parent window is disabled, but not to the other ones. ``PD_AUTO_HIDE`` 0x4 Causes the progress dialog to disappear from screen as soon as the maximum value of the progress meter has been reached. ``PD_ELAPSED_TIME`` 0x8 This flag tells the dialog that it should show elapsed time (since creating the dialog). =================== =========== ================================================== """ wx.Dialog.__init__(self, parent, id, title) self._delay = 3 self._hasAbortButton = False # we may disappear at any moment, let the others know about it self.SetExtraStyle(self.GetExtraStyle()|wx.WS_EX_TRANSIENT) self._hasAbortButton = (agwStyle & wx.PD_CAN_ABORT) if wx.Platform == "__WXMSW__": # we have to remove the "Close" button from the title bar then as it is # confusing to have it - it doesn't work anyhow # FIXME: should probably have a (extended?) window style for this if not self._hasAbortButton: self.EnableClose(False) self._state = (self._hasAbortButton and [Continue] or [Uncancelable])[0] self._parentTop = wx.GetTopLevelParent(parent) dc = wx.ClientDC(self) dc.SetFont(wx.SystemSettings.GetFont(wx.SYS_DEFAULT_GUI_FONT)) widthText, dummy = dc.GetTextExtent(message) sizer = wx.BoxSizer(wx.VERTICAL) self._msg = wx.StaticText(self, wx.ID_ANY, message) sizer.Add(self._msg, 0, wx.LEFT|wx.TOP, 2*LAYOUT_MARGIN) sizeDlg = wx.Size() sizeLabel = self._msg.GetSize() sizeDlg.y = 2*LAYOUT_MARGIN + sizeLabel.y self._gauge = ProgressGauge(self, -1) sizer.Add(self._gauge, 0, wx.LEFT|wx.RIGHT|wx.TOP|wx.EXPAND, 2*LAYOUT_MARGIN) sizeGauge = self._gauge.GetSize() sizeDlg.y += 2*LAYOUT_MARGIN + sizeGauge.y # create the estimated/remaining/total time zones if requested self._elapsed = None self._display_estimated = self._last_timeupdate = self._break = 0 self._ctdelay = 0 label = None nTimeLabels = 0 if agwStyle & wx.PD_ELAPSED_TIME: nTimeLabels += 1 self._elapsed = self.CreateLabel("Elapsed time : ", sizer) if nTimeLabels > 0: label = wx.StaticText(self, -1, "") # set it to the current time self._timeStart = int(time.time()) sizeDlg.y += nTimeLabels*(label.GetSize().y + LAYOUT_MARGIN) label.Destroy() sizeDlgModified = False if wx.Platform == "__WXMSW__": sizerFlags = wx.ALIGN_RIGHT|wx.ALL else: sizerFlags = wx.ALIGN_CENTER_HORIZONTAL|wx.BOTTOM|wx.TOP if self._hasAbortButton: buttonSizer = wx.BoxSizer(wx.HORIZONTAL) self._btnAbort = wx.Button(self, -1, "Cancel") self._btnAbort.Bind(wx.EVT_BUTTON, self.OnCancel) # Windows dialogs usually have buttons in the lower right corner buttonSizer.Add(self._btnAbort, 0, sizerFlags, LAYOUT_MARGIN) if not sizeDlgModified: sizeDlg.y += 2*LAYOUT_MARGIN + wx.Button.GetDefaultSize().y if self._hasAbortButton: sizer.Add(buttonSizer, 0, sizerFlags, LAYOUT_MARGIN ) self.Bind(wx.EVT_CLOSE, self.OnClose) self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy) self._agwStyle = agwStyle self.SetSizerAndFit(sizer) sizeDlg.y += 2*LAYOUT_MARGIN # try to make the dialog not square but rectangular of reasonable width sizeDlg.x = max(widthText, 4*sizeDlg.y//3) sizeDlg.x *= 3 sizeDlg.x //= 2 self.SetClientSize(sizeDlg) self.Centre(wx.CENTER|wx.BOTH) if agwStyle & wx.PD_APP_MODAL: self._winDisabler = wx.WindowDisabler(self) else: if self._parentTop: self._parentTop.Disable() self._winDisabler = None self.ShowDialog() self.Enable() # this one can be initialized even if the others are unknown for now # NB: do it after calling Layout() to keep the labels correctly aligned if self._elapsed: self.SetTimeLabel(0, self._elapsed) if not wx.GUIEventLoop().GetActive(): self.evtloop = wx.GUIEventLoop() wx.GUIEventLoop.SetActive(self.evtloop) self.Update()
self.display_num = 0 def add(self, d): self.displays.append(d) def remove(self, d): self.displays.remove(d) def paint_displays(self): for d in self.displays: d._paint() _displays = _ManageDisplays() displays = _displays.displays _evtloop = _wx.GUIEventLoop() _wx.EventLoop.SetActive(_evtloop) _isMac = ('wxOSX' in _wx.PlatformInfo) if _plat == 'Windows': # On Windows, the best timer is supposedly time.clock() _clock = _time.clock else: # On most other platforms, the best timer is supposedly time.time() _clock = _time.time ##_lastInteract = None ## ### This thread watches to see whether the window has become inactive, ### typically due to a loop not containing a call to rate or sleep. ### The check for "_lastInteract is not None" means that a program
# ファイル書き込みイベント def OnSave(self, event): self.controlPanel.Save("record.txt") wx.MessageBox('Saveed') # 終了イベント def OnExit(self, event): self.Close() if __name__ == '__main__': app = wx.App() mf = MainFrame() ap = AutoProcess() # app.MainLoop() evtloop = wx.GUIEventLoop() evtloop = wx.EventLoop() wx.EventLoop.SetActive(evtloop) mf.boardPanel.SetDrawFlag(True) """Drives the main wx event loop.""" i = 0 while 1: while evtloop.Pending( ): # if there is at least one event to be processed evtloop.Dispatch() # process one event #~ time.sleep(0.10)
def MainLoop(self): evtloop = wx.GUIEventLoop() wx.EventLoop.SetActive(evtloop) module_names = [] for module in (name for name, _ in shm.vision_modules._fields): try: module_file = imp.reload(__import__(module)) except: print('Could not load {}'.format(module)) continue multiple_modules = len(module_file.capture_source.split()) > 1 if multiple_modules: for capture_source in module_file.capture_source.split(): module_names.append('{}.{}'.format(module, capture_source)) else: module_names.append(module) added_modules = {} while True: start_time = time.time() try: location = 0 for module in module_names: if getattr(shm.vision_modules, module.split('.')[0]).get(): if module not in self.options_shared_memory: if module in added_modules: continue added_modules[module] = True try: options_shm = mmap.mmap(posix_ipc.SharedMemory('/{}_module_options'.format(module), posix_ipc.O_CREAT | posix_ipc.O_RDWR).fd, 0) options_lock = vision_common.NamedRWLock('{}_module_lock'.format(module), owner=False) self.options_shared_memory[module] = options_shm, options_lock module_socket = self.zmq_context.socket(zmq.SUB) module_socket.setsockopt(zmq.RCVHWM, 1) module_socket.setsockopt(zmq.SUBSCRIBE, module) module_socket.connect('ipc:///tmp/visiond_module_socket_{}'.format(module)) module_socket.RCVTIMEO = 5 self.options_zmq_sockets[module] = module_socket except posix_ipc.ExistentialError: return else: options_shm, options_lock = self.options_shared_memory[module] module_socket = self.options_zmq_sockets[module] images = [] try: module_socket.recv_string() # throw away tag while True: to_decode = module_socket.recv() md = json.loads(to_decode) buf = buffer(module_socket.recv(copy=False)) img = np.frombuffer(buf, dtype=md['dtype']) images.append((md['tag'], img.reshape(md['shape']))) except (zmq.error.Again, ValueError): pass options_lock.acquire_read() options_shm.seek(0) length = struct.unpack('I', options_shm.read(4))[0] options = [] while length > 0: options.append(json.loads(options_shm.read(length))) length = struct.unpack('I', options_shm.read(4))[0] options_lock.release_read() if module not in self.pages: self.init_page(module, options, location) self.update(module, images, options) location += 1 elif module in self.pages: self.remove(module) del self.pages[module] while evtloop.Pending(): evtloop.Dispatch() except wx.PyDeadObjectError: pass except Exception as e: print(e) traceback.print_exc(e) rem = 0.1 - (time.time() - start_time) if rem > 0: time.sleep(rem)