自动刷新配合面板小程序

时间:2018-03-26 18:32:34

标签: python ubuntu applet gtk mate

Ubuntu限制你可以用时区做什么 - 大多数应用程序都对/ etc / localtime有很强的依赖性,包括mate-panel中的Clock 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)

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

1 个答案:

答案 0 :(得分:0)

问题出在calc_datetime

  1. 使用idle_add添加的函数返回True或False,它确定是否应再次调用此函数。
  2. 在mainloop中调用此idle_added函数。在那里,您可以更新所有标签。