Skip to content

Instantly share code, notes, and snippets.

@jampola
Last active April 3, 2023 08:56
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jampola/473e963cff3d4ae96707 to your computer and use it in GitHub Desktop.
Save jampola/473e963cff3d4ae96707 to your computer and use it in GitHub Desktop.
Simple clock using PyGTK and GObject.timeout_add()
#!/usr/bin/python
from gi.repository import Gtk, GObject
from datetime import datetime
class MainWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="app")
self.box = Gtk.Box(spacing=6)
self.add(self.box)
self.label = Gtk.Label()
self.box.pack_start(self.label, True, True, 0)
# Displays Timer
def displayclock(self):
# putting our datetime into a var and setting our label to the result.
# we need to return "True" to ensure the timer continues to run, otherwise it will only run once.
datetimenow = str(datetime.now())
self.label.set_label(datetimenow)
return True
# Initialize Timer
def startclocktimer(self):
# this takes 2 args: (how often to update in millisec, the method to run)
GObject.timeout_add(1000, self.displayclock)
win = MainWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
win.startclocktimer()
Gtk.main()
@jampola
Copy link
Author

jampola commented Oct 8, 2014

I was helping a student out with some basic timer/threading concepts and found there was nothing simple that was searchable via google. Hopefully this helps someone out. Please TRY and understand what is going on (especially here: http://www.pygtk.org/pygtk2reference/gobject-functions.html#function-gobject--timeout-add) and not just copy and paste. You'll thank me later! :)

edit: There is one problem with this. Upon opening the program for the first time, it takes an initial 1000ms to initially display the time... how could you solve it in the least amount of steps? Enjoy!

@guidugli
Copy link

guidugli commented Jan 2, 2018

thank you

@christopolise
Copy link

Thank you

@GPoleto27
Copy link

Answering your edit:
Simply call displayclock() on the init function and then call startclocktimer()
If you call that function before Gtk.main() it will always delay your startup, so, get rid of that

@MJtuks
Copy link

MJtuks commented Sep 29, 2020

Thank you for this

@kontrarie
Copy link

Many thanks, this got me out of an issue that had been haunting me for a long while.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment