Search code examples
pythongtk

Run a schedule with python GTK


I'm building a GTK application with Python but I want to update labels at a specific time every hour.

I tried with schedule but apparently it doesn't work with pygobject. This is my sample code

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)

Update Thanks for the answer of JohnKoch, this solution was applied to my repo that works as TOTP Authenticator on Linux, You can visit and I will appreciate it very much if you leave a star or any issues about my repo.


Solution

  • Gtk.main()

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

    So schedule below never has the chance to run. You need to hook a function to Gtk main loop, for example, by calling GLib.timeout_add.

    Here is an example,

    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()