问题
i am writing an Indicator in Python which should update every 5 minutes. Unfortunately the label is updated only 3 times, but then the label stays the same, although the thread still runs.
For demonstration purpose, I replaced the data with the current time.
#!/usr/bin/env python3
import signal
import gi
import threading
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, AppIndicator3, GObject
import time
class Indicator():
def __init__(self):
self.app = 'turtle-mining-indicator'
self.menu = {}
self.indicator = AppIndicator3.Indicator.new(
self.app, ICON,
AppIndicator3.IndicatorCategory.OTHER)
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
self.indicator.set_menu(self.create_menu())
self.indicator.set_label("Starting ...", self.app)
self.scheduler()
def update(self):
print("update " + time.asctime())
self.indicator.set_label(time.asctime(), self.app)
self.menu["first"].set_label("First: " + time.asctime())
def scheduler(self):
self.update()
self.timer = threading.Timer(3, self.scheduler).start()
def create_menu(self):
menu = Gtk.Menu()
self.menu["first"] = Gtk.MenuItem("First")
menu.append(self.menu["first"])
menu.show_all()
return menu
Indicator()
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()
I don't understand, why this happens. The method update() gets executed but the set_label method only works 3 times. What am I doing wrong?
回答1:
Mixing threads and Gtk is just plain wrong. GLib.timeout_add_seconds() is made specifically for this reason. Here is the proper way to do timely updates:
#!/usr/bin/env python3
import signal
import gi
gi.require_version('Gtk', '3.0')
gi.require_version('AppIndicator3', '0.1')
from gi.repository import Gtk, AppIndicator3, GLib
import time
class Indicator():
def __init__(self):
self.app = 'turtle-mining-indicator'
self.menu = {}
self.indicator = AppIndicator3.Indicator.new(
self.app, "my indicator",
AppIndicator3.IndicatorCategory.OTHER)
self.indicator.set_status(AppIndicator3.IndicatorStatus.ACTIVE)
self.indicator.set_menu(self.create_menu())
self.indicator.set_label("Starting ...", self.app)
GLib.timeout_add_seconds (1, self.update)
def update(self):
print("update " + time.asctime())
self.indicator.set_label(time.asctime(), self.app)
self.menu["first"].set_label("First: " + time.asctime())
return True
def create_menu(self):
menu = Gtk.Menu()
self.menu["first"] = Gtk.MenuItem("First")
menu.append(self.menu["first"])
menu.show_all()
return menu
Indicator()
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()
来源:https://stackoverflow.com/questions/49218749/python-indicator-stops-updating-after-3-times-on-ubuntu