ubuntu限制了您可以使用时区的操作 - 大多数应用程序都对/etc/localtime(包括Mate -Panel中的时钟applet(都具有很大的依赖性。我正在尝试编写一个python applet,以显示用户选择的时区中的时间,但我无法自动刷新 - 我想每1秒显示当前时间。
#!/usr/bin/env python
from datetime import datetime
from time import gmtime, strftime, sleep
import pytz
from os.path import expanduser
from os.path import exists
import gi
TIMEZONE = 'Australia/Sydney'
DATE_FMT = '%Y-%m-%d %H:%M:%S'
gi.require_version("Gtk", "2.0")
gi.require_version("MatePanelApplet", "4.0")
from gi.repository import GObject, Gtk, MatePanelApplet
# I moved this code out of applet_fill() and into its own function
# so that I can call it with Gtk.timeout_add or GObject.timeout_add
# ...but I get the dreaded white dot when reloading the app.
def calc_datetime(applet, timezone):
dt_xxx = pytz.timezone(strftime("%Z", gmtime())).localize(datetime.now()).astimezone(pytz.timezone(timezone)).strftime(DATE_FMT)
DateLabel = Gtk.Label(timezone + ':- ' + dt_xxx)
applet.add(DateLabel)
applet.show_all()
# DateLabel.set_text() works, but not when looped.
#while True:
# DateLabel.set_text('Hello')
# sleep(1)
return DateLabel
def applet_fill(applet):
# define custom timezone in ~/.config/company/timezone
cfg_file = expanduser('~') + '/.config/company/timezone'
if exists(cfg_file):
with open(expanduser('~') + '/.config/company/timezone', 'r') as file:
timezone = file.read().replace('n', '')
else:
timezone = TIMEZONE
DateLabel = calc_datetime(applet, timezone)
# I atempted different things here, but again, white dot in the panel.
#i = 1
#while True:
# sleep(1)
# DateLabel.set_text('test again')
# #i = i + 1
# GObject.idle_add(calc_datetime, applet, timezone)
#Gtk.timeout_add('100', calc_datetime, applet, timezone)
#DateLabel.set_text('test')
#return True
# this is called by mate-panel on applet creation
def applet_factory(applet, iid, data):
if iid != "MyClockApplet":
return False
applet_fill(applet)
return True
MatePanelApplet.Applet.factory_main("MyClockAppletFactory", True, MatePanelApplet.Applet.__gtype__, applet_factory, None)
我在代码注释中放了笔记。
问题在calc_datetime
- 您使用
idle_add
返回true或false添加的函数,该函数确定是否应再次调用此函数。 - 此IDLE_ADDED功能在Mainloop中调用。在那里您可以更新所有标签。