运行 使用 python GTK 的时间表

Run a schedule with python GTK

我正在使用 Python 构建 GTK 应用程序,但我想每小时在特定时间更新标签。

我试过 schedule 但显然它不适用于 pygobject。这是我的示例代码

application = Application()
application.connect("destroy", Gtk.main_quit)
application.show_all()
Gtk.main()

print('go here') # This line never run
schedule.every(30).seconds.do(application.update_code)

while 1:
    schedule.run_pending()
    time.sleep(1)

更新感谢JohnKoch的回答,这个解决方案已经应用到my repo,在Linux上作为TOTP Authenticator,你可以访问我如果您留下一个星星或任何关于我的回购的问题,将不胜感激。

Gtk.main()

Runs the main loop until Gtk.main_quit() is called.

所以下面的时间表永远没有机会运行。您需要将函数挂接到 Gtk 主循环,例如,通过调用 GLib.timeout_add.

这是一个例子,

import gi

gi.require_version("Gtk", "3.0")
from gi.repository import GLib, Gtk

import schedule

window = Gtk.Window(title="Hello World")
window.set_default_size(600, 400)
window.connect("destroy", Gtk.main_quit)

label = Gtk.Label(label="0")
window.add(label)
window.show_all()

count = 0

def update_label():
    global count
    count = count + 1
    label.set_text(str(count))

schedule.every(2).seconds.do(update_label)

def run_schedule():
    schedule.run_pending()
    return True

GLib.timeout_add(1000, lambda: run_schedule())

Gtk.main()