Update Label Continuously With Glib Timout
Python gi.repository.GLib.timeout_add() Examples
The following are 30 code examples of gi.repository.GLib.timeout_add() . 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 gi.repository.GLib , or try the search function .
Example #1
def _update_overlay(self, auto = False): ffbmeter_overlay = self.ffbmeter_overlay.get_active() wheel_range_overlay = self.get_wheel_range_overlay() if ffbmeter_overlay or wheel_range_overlay == 'always' or (wheel_range_overlay == 'auto' and auto): if not self.overlay_window.props.visible: self.overlay_window.show() if not self.ffbmeter_timer and self.overlay_window.props.visible and ffbmeter_overlay: GLib.timeout_add(250, self.update_ffbmeter_overlay) if ffbmeter_overlay: self._ffbmeter_overlay.show() else: self._ffbmeter_overlay.hide() if wheel_range_overlay == 'always' or (wheel_range_overlay == 'auto' and auto): self._wheel_range_overlay.show() else: self._wheel_range_overlay.hide() else: self.overlay_window.hide()
Example #2
def _gtk_configure(self, widget, event): def resize(*args): self._resize_timer_id = None width, height = self._window.get_size() columns = width // self._cell_pixel_width rows = height // self._cell_pixel_height if self._screen.columns == columns and self._screen.rows == rows: return self._bridge.resize(columns, rows) if not self._screen: return if event.width == self._pixel_width and \ event.height == self._pixel_height: return if self._resize_timer_id is not None: GLib.source_remove(self._resize_timer_id) self._resize_timer_id = GLib.timeout_add(250, resize)
Example #3
def on_btn_start_clicked(self, _widget): """Handle btn_start.clicked event.""" seconds = int(self.adj_seconds.get_value()) self.spawn_process.spawn('iperf -s -xS -yC'.split(), timeout=(seconds + 3), lines_max=2*len(self.clients)) for client in self.clients: handle = self.clients[client][0] # Half time for upload speed and half for download self.execute(handle, 'start_benchmark %d' % int(seconds/2)) self.timeleft = seconds self.box_seconds.set_visible(False) self.box_countdown.set_visible(True) self.btn_start.set_visible(False) self.btn_stop.set_visible(True) self.lbl_countdown.set_text(_("Benchmark finishing in %d seconds...") % self.timeleft) self.countdown_event = GLib.timeout_add(1000, self.update_countdown)
Example #4
def connect(self): """Handle btn_action clicked when it's in the Connect state.""" self.host = self.ent_host.get_text().strip() pid = os.getpid() share_terminal = self.cmb_method.get_active() != 0 if share_terminal: cmd = ['xterm', '-e', os.path.dirname(__file__) + '/share-terminal', self.host] subprocess.Popen(cmd) self.on_btn_close_clicked(None) return cmd = ['x11vnc', '-q', '-nopw', '-connect_or_exit', self.host, '-afteraccept', 'kill -USR1 {}'.format(pid)] self.proc = subprocess.Popen(cmd) # Set the status as "Connecting" if self.retry_timeout_id: GLib.source_remove(self.retry_timeout_id) self.retry_timeout_id = None self.set_state('connecting') # Start polling the process every 1 second to see if it's still alive GLib.timeout_add(1000, self.poll_process)
Example #5
def assert_valid_output_file(output_video_location): ''' Given a file, validates it is a video (mp4) file ''' import gi gi.require_version('Gst', '1.0') from gi.repository import Gst, GLib Gst.init(None) mainloop = GLib.MainLoop() # We create a pipeline so that we can read the file and check it: pipeline = Gst.ElementFactory.make("playbin") pipeline.set_property('uri','file://'+output_video_location) playsink = pipeline.get_by_name('playsink') playsink.set_property('video-sink', Gst.ElementFactory.make('fakesink')) pipeline.set_state(Gst.State.PAUSED) def after_a_second(): assert pipeline.get_state(0).state == Gst.State.PAUSED element = pipeline.get_by_name('inputselector1') caps = element.get_static_pad('src').get_current_caps() assert caps.to_string() == 'audio/x-raw, format=(string)F32LE, layout=(string)interleaved, rate=(int)48000, channels=(int)2, channel-mask=(bitmask)0x0000000000000003' element = pipeline.get_by_name('inputselector0') caps = element.get_static_pad('src').get_current_caps() assert caps.to_string() == 'video/x-raw, format=(string)NV12, width=(int)640, height=(int)360, interlace-mode=(string)progressive, multiview-mode=(string)mono, multiview-flags=(GstVideoMultiviewFlagsSet)0:ffffffff:/right-view-first/left-flipped/left-flopped/right-flipped/right-flopped/half-aspect/mixed-mono, pixel-aspect-ratio=(fraction)1/1, chroma-site=(string)jpeg, colorimetry=(string)bt601, framerate=(fraction)30/1' pipeline.set_state(Gst.State.NULL) mainloop.quit() GLib.timeout_add(1000, after_a_second) mainloop.run()
Example #6
def rebuild(self): """ Rebuild. """ if not self.active: return # Don't rebuild, we are hidden. if self.load < 3: # avoid to load the database twice return self.total = self.dbstate.db.get_number_of_people() self._erase_name_selection() active = self.get_active() if active != "": self.on_draw_ok = -1 self.people, self.families, self.layers = self.read_data(active) self.canvas.queue_draw() self.canvas.grab_focus() # We need to wait on_draw is called to draw path lines. self.on_draw_ok = 0 GLib.timeout_add(int(200), self.after_on_draw_on_rebuild)
Example #7
def show_family_name(self, handle, event): """ Popup menu for node (family). """ if handle: family = self.dbstate.db.get_family_from_handle(handle) else: return False if family: if not self.timeout: self.save_tooltip = handle self.scrolledwindow.set_property("has-tooltip", True) tooltip = self.get_family_name(handle) self.scrolledwindow.set_tooltip_text(tooltip) self.timeout = GLib.timeout_add(3*1000, self.remove_tooltip) elif handle != self.save_tooltip: self.save_tooltip = handle GLib.source_remove(self.timeout) tooltip = self.get_family_name(handle) self.scrolledwindow.set_tooltip_text(tooltip) self.timeout = GLib.timeout_add(3*1000, self.remove_tooltip)
Example #8
def run(self): self.loop = GLib.MainLoop() if self.config.notifications: try: notify2.init("pantalaimon", mainloop=self.loop) self.notifications = True except dbus.DBusException: logger.error( "Notifications are enabled but no notification " "server could be found, disabling notifications." ) self.notifications = False GLib.timeout_add(100, self.message_callback) if not self.loop: return self.loop.run()
Example #9
def on_touch(self, widget, event): """Clear mouse connection when touching screen. This stops calling the ButtonX bindings when using the touch screen. Reasoning: We do not want to e.g. move to the next image when trying to zoom in. """ try: self._app["window"].disconnect_by_func(self.on_click) # Was already disconnected except TypeError: pass if self._timer_id_touch: GLib.source_remove(self._timer_id_touch) self._timer_id_touch = GLib.timeout_add(5, self._reconnect_click) return True
Example #10
def timer(self, name, delay, callback, *data, **kwdata): """ Runs callback after specified number of seconds. Uses GLib.timeout_add_seconds with small wrapping to allow named timers to be canceled by reset() call """ method = GLib.timeout_add_seconds if delay < 1 and delay > 0: method = GLib.timeout_add delay = delay * 1000.0 if name is None: # No wrapping is needed, call GLib directly method(delay, callback, *data, **kwdata) else: if name in self._timers: # Cancel old timer GLib.source_remove(self._timers[name]) # Create new one self._timers[name] = method(delay, self._callback, name, callback, *data, **kwdata)
Example #11
def enable_all_plots(self, *args): self.plotcanvas.clear() self.set_progress_bar(0.1, "Re-plotting...") def worker_task(app_obj): percentage = 0.1 try: delta = 0.9 / len(self.collection.get_list()) except ZeroDivisionError: GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, "")) return for obj in self.collection.get_list(): obj.options['plot'] = True obj.plot() percentage += delta GLib.idle_add(lambda: app_obj.set_progress_bar(percentage, "Re-plotting...")) GLib.idle_add(app_obj.plotcanvas.auto_adjust_axes) GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, "")) # Send to worker self.worker.add_task(worker_task, [self])
Example #12
def on_update_plot(self, widget): """ Callback for button on form for all kinds of objects. Re-plots the current object only. :param widget: The widget from which this was called. Ignored. :return: None """ obj = self.collection.get_active() obj.read_form() self.set_progress_bar(0.5, "Plotting...") def thread_func(app_obj): assert isinstance(app_obj, App) obj.plot() GLib.timeout_add(300, lambda: app_obj.set_progress_bar(0.0, "Idle")) # Send to worker self.worker.add_task(thread_func, [self])
Example #13
def on_pane_event(self, widget, evt): """ Signal handler for gtk.paned events. This function allows one to delay drawing events when resizing, and to speed up redrawing when moving the middle pane is done (which happens at the end of a mouse resize) Args: widget (:class:`~Gtk.Widget`): the widget in which the event occurred (ignored) evt (:class:`~Gdk.Event`): the event that occurred """ if type(evt) == Gdk.EventButton and evt.type == Gdk.EventType.BUTTON_RELEASE: self.redraw_panes() elif type(evt) == GObject.GParamSpec and evt.name == "position": self.resize_panes = True if self.redraw_timeout: GLib.Source.remove(self.redraw_timeout) self.redraw_timeout = GLib.timeout_add(200, self.redraw_panes) ############################################################################ ############################ Program lifetime ############################ ############################################################################
Example #14
def state_loop(self, scroll_scale=None, delay=16): # 16ms ~ 60hz # Remove any pending callbacks if self.timeout_id: GLib.source_remove(self.timeout_id) self.timeout_id = None # Set scroll scale if specified, and the state is not dirty if not self.state_discard_read and scroll_scale not in (None, self.scroll_scale): self.scroll_scale = scroll_scale if self.scroll_scale != -1: self.emit("scroll-scale-changed", self.scroll_scale) self.state_discard_read = False # Handle the current state if not self.state_loaded or self.state_load_failed or self.state_waiting: return elif self.state_dirty or delay == 0: self.sync_scroll_scale(self.scroll_scale, self.state_dirty) self.state_dirty = False else: self.timeout_id = GLib.timeout_add(delay, self.state_loop, None, 0)
Example #15
def play(self): if self.uri.endswith(".MP4"): self.is_playing = True else: self.is_playing = False cli.log.info(_("play")) self.player.set_state(Gst.State.PLAYING) # starting up a timer to check on the current playback value GLib.timeout_add(1000, self.update_slider)
Example #16
def delayed_signal(delay=500): """ A decorator to delay the execution of a signal handler to aggregate emission into a single event. This can for example be used to run a handler when a :py:class:`Gtk.Entry` widget's ``changed`` signal is emitted but not after every single key press meaning the handler can perform network operations to validate or otherwise process input. .. note:: The decorated function **must** be a method. The wrapper installed by this decorator will automatically add an attribute to the class to track invoked instances to ensure the timeout is respected. .. versionadded:: 1.14.0 :param int delay: The delay in milliseconds from the original emission before the handler should be executed. """ def decorator(function): src_name = '__delayed_source_' + function.__name__ @functools.wraps(function) def wrapped(self, *args, **kwargs): def new_function(self, *args, **kwargs): setattr(self, src_name, None) return function(self, *args, **kwargs) src = getattr(self, src_name, None) if src is not None: return src = GLib.timeout_add(delay, new_function, self, *args, **kwargs) setattr(self, src_name, src) return wrapped return decorator
Example #17
def run(self, *args): GLib.timeout_add(1000, self.callback, *args) GLib.timeout_add(500, self.blinking) Gtk.main()
Example #18
def set_btn_input(self, index, value, wait = None): if wait != None: GLib.timeout_add(wait, lambda index=index, value=value: GLib.idle_add(self.set_btn_input, index, value) & False) else: GLib.idle_add(self.btn_input[index].set_value, value)
Example #19
def _start_blinking(self): def blink(*args): self._blink = not self._blink self._screen_invalid() self._blink_timer_id = GLib.timeout_add(500, blink) if self._blink_timer_id: GLib.source_remove(self._blink_timer_id) self._blink = False blink()
Example #20
def got_thumbshot(self, handle, reply): """Callback after running`thumbshot` on a client.""" for i in self.cstore: if handle == i[C_SESSION_HANDLE]: # We want to ask for thumbshots every 5 sec after the last one. # So if the client is too stressed and needs 7 secs to # send a thumbshot, we'll ask for one every 12 secs. GLib.timeout_add(5000, self.ask_thumbshot, handle) LOG.d("I got a thumbshot from %s." % handle) if not reply: return try: rowstride, size, pixels = reply.split(b'\n', 2) rowstride = int(rowstride) width, height = [int(i) for i in size.split(b'x')] except ValueError: LOG.e("Bad thumbshot header") return # GLib.Bytes.new and .copy() avoid memory leak and crash (#110) pxb = GdkPixbuf.Pixbuf.new_from_bytes( GLib.Bytes.new(pixels), GdkPixbuf.Colorspace.RGB, False, 8, width, height, rowstride) pxb = pxb.copy() self.current_thumbshots[handle] = pxb self.cstore[i.path][C_PIXBUF] = pxb return # That handle is no longer in the cstore, remove it if handle in self.current_thumbshots: del self.current_thumbshots[handle]
Example #21
def update_and_retry(self, msg, interval): """Show a "Retrying in 10..." label, and then retry.""" if interval == 0: self.on_btn_action_clicked(None) else: self.lbl_status.set_text( msg + ' ' + _('Retrying in %d...') % interval) self.retry_timeout_id = GLib.timeout_add( 1000, self.update_and_retry, msg, interval - 1) return False
Example #22
def _timer_start(self): # Need to stop it, otherwise we potentially leak a timer id that will # never be stopped. self._timer_stop() self._timer = GLib.timeout_add(self._interval, self._on_timer)
Example #23
def _on_timer(self): TimerBase._on_timer(self) # Gtk timeout_add() requires that the callback returns True if it # is to be called again. if self.callbacks and not self._single: return True else: self._timer = None return False
Example #24
def __init__(self): GLib.set_prgname('kickoff-player') GLib.set_application_name('Kickoff Player') add_custom_css('ui/styles.css') self.argparse = argparse.ArgumentParser(prog='kickoff-player') self.argparse.add_argument('url', metavar='URL', nargs='?', default=None) self.cache = CacheHandler() self.data = DataHandler() self.scores_api = ScoresApi(self.data, self.cache) self.streams_api = StreamsApi(self.data, self.cache) self.main = Gtk.Builder() self.main.add_from_file(relative_path('ui/main.ui')) self.main.connect_signals(self) self.window = self.main.get_object('window_main') self.header_back = self.main.get_object('header_button_back') self.header_reload = self.main.get_object('header_button_reload') self.main_stack = self.main.get_object('stack_main') self.player_stack = self.main.get_object('stack_player') self.matches_stack = self.main.get_object('stack_matches') self.channels_stack = self.main.get_object('stack_channels') self.matches = MatchHandler(self) self.channels = ChannelHandler(self) self.player = PlayerHandler(self) GLib.timeout_add(2000, self.toggle_reload, True) self.open_stream_url()
Example #25
def __init__(self, app): self.app = app self.stack = app.matches_stack self.filter = None self.matches = Gtk.Builder() self.matches.add_from_file(relative_path('ui/matches.ui')) self.matches.connect_signals(self) self.matches_box = self.matches.get_object('box_matches') self.stack.add_named(self.matches_box, 'matches_container') self.matches_filters = self.matches.get_object('list_box_matches_filters') self.matches_list = self.matches.get_object('flow_box_matches_list') self.matches_list.set_filter_func(self.on_matches_list_row_changed) self.match = Gtk.Builder() self.match.add_from_file(relative_path('ui/match.ui')) self.match.connect_signals(self) self.match_box = self.match.get_object('box_match') self.stack.add_named(self.match_box, 'match_container') self.match_teams = self.match.get_object('box_match_teams') self.match_streams = self.match.get_object('list_box_match_streams') GLib.idle_add(self.do_initial_setup) GLib.idle_add(self.do_matches_widgets) GLib.timeout_add(5 * 60000, self.update_live_data)
Example #26
def on_eventbox_motion_notify_event(self, _widget, _event): self.toolbar_stick = False GLib.source_remove(self.toolbar_event) GLib.idle_add(self.toggle_toolbar, False) self.toolbar_event = GLib.timeout_add(3000, self.toggle_toolbar, True)
Example #27
def init(self): """ Initialize gramplet. Start up update timer. """ self.limit = 5 # Description, Type, URL, Pretty URL for User self.feeds = [ ("Gramps Wiki Headline News", "wiki", (self.RAW % "HeadlineNews"), (self.URL % "HeadlineNews")), ("Gramps Blog Posts", "rss", "https://gramps-project.org/introduction-WP/?feed=rss", None), ("Gramps Bugtracker Issues", "rss", "https://gramps-project.org/bugs/issues_rss.php?" "key=ece7d21451d76337acf776c9a4384773", None), ("Gramps Wiki Changes", "rss", "https://gramps-project.org/wiki/index.php?title=" "Special:RecentChanges&feed=rss", None), ] # # Needs ATOM support to work # ("Github Gramps Git Commits", "atom", # "https://github.com/gramps-project/gramps/commits/master.atom", # None), # ("Reddit Gramps - fan-run forum(unofficial)", "atom", # "https://www.reddit.com/r/gramps/.rss", None), # # Comments no longer used on blog due to SPAM! # ("Gramps Blog Comments", "rss", # "https://gramps-project.org/introduction-WP/?" # "feed=comments-rss2", None), self.set_tooltip(_("Read Gramps headline news")) self.update_interval = (3600 * 1000) * 24 # in miliseconds (24 hours) self.set_use_markup(True) self.set_wrap(False) self.set_text(_("No Family Tree loaded.")) self.timer = GLib.timeout_add(self.update_interval, self.update_by_timer)
Example #28
def apply_spinner_delayed(self, widget, conf_const): """ Set params by spinners (generations, spacing). Use timeout for better interface responsiveness. """ value = int(widget.get_value()) # try to remove planed event (changing setting) if self.timeout_event and \ not self.timeout_event.is_destroyed(): GLib.source_remove(self.timeout_event.get_id()) # timeout saving setting for better interface responsiveness event_id = GLib.timeout_add(300, self.view._config.set, conf_const, value) context = GLib.main_context_default() self.timeout_event = context.find_source_by_id(event_id)
Example #29
def _timer_start(self): # Need to stop it, otherwise we potentially leak a timer id that will # never be stopped. self._timer_stop() self._timer = GLib.timeout_add(self._interval, self._on_timer)
Example #30
def _on_timer(self): TimerBase._on_timer(self) # Gtk timeout_add() requires that the callback returns True if it # is to be called again. if len(self.callbacks) > 0 and not self._single: return True else: self._timer = None return False
Source: https://www.programcreek.com/python/example/88997/gi.repository.GLib.timeout_add
0 Response to "Update Label Continuously With Glib Timout"
Post a Comment