1

Ubuntu 限制了您可以对时区执行的操作 - 大多数应用程序都严重依赖 /etc/localtime,包括 mate-panel 中的 Clock 小程序。我正在尝试编写一个 python 小程序来显示用户选择的时区的时间,但我无法让它自动刷新 - 我想每 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)

我在代码注释中添加了注释。

4

1 回答 1

1

问题出在calc_datetime

  1. 您添加的函数idle_add返回 True 或 False,这决定了是否应该再次调用此函数。
  2. 这个 idle_added 函数在 mainloop 中被调用。在那里您可以更新所有标签。
于 2018-03-27T22:09:44.527 回答