gpt4 book ai didi

python - 自动刷新伴侣面板小程序

转载 作者:太空宇宙 更新时间:2023-11-03 13:57:22 24 4
gpt4 key购买 nike

Ubuntu 限制了您可以使用时区执行的操作 - 大多数应用程序都严格依赖于/etc/localtime,包括 mate-panel 中的时钟小程序。我正在尝试编写一个 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)

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

最佳答案

问题出在calc_datetime

  1. 使用 idle_add 添加的函数返回 True 或 False,这决定是否应再次调用该函数。
  2. 这个idle_added函数在主循环中被调用。您可以在那里更新所有标签。

关于python - 自动刷新伴侣面板小程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49498316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com