1

I was trying to build a simple stopwatch app using py-gtk. Here is the callback function for the toggle button in my stopwatch window.

def start(self,widget):
    if widget.get_active():         
        widget.set_label('Stop')
    else: 
        self.entry.set_text(str(time.time() - s))   
        widget.set_label('Start')

It works perfectly well except for the fact that time does not get continuously get displayed in the entry widget. If I add an infinite while loop inside the 'If ' condition like ,

while 1:
    self.entry.set_text(str(time.time() - s))

the window becomes unresponsive. Can someone help?

Manoj
  • 961
  • 4
  • 11
  • 37

1 Answers1

4

Use gobject.timeout_add:

gobject.timeout_add(500, self.update)

to have gtk call self.update() every 500 milliseconds.

In the update method check if the stopwatch is active and call

self.entry.set_text(str(time.time() - s))   

as necessary.


Here is fairly short example which draws a progress bar using gobject.timeout_add:

import pygtk
pygtk.require('2.0')
import gtk
import gobject
import time

class ProgressBar(object):
    def __init__(self):
        self.val = 0
        self.scale = gtk.HScale()
        self.scale.set_range(0, 100)
        self.scale.set_update_policy(gtk.UPDATE_CONTINUOUS)
        self.scale.set_value(self.val)
        gobject.timeout_add(100, self.timeout)
    def timeout(self):
        self.val += 1
        # time.sleep(1)
        self.scale.set_value(self.val)
        return True

def demo_timeout_add():
    # http://faq.pygtk.org/index.py?req=show&file=faq23.020.htp
    # http://stackoverflow.com/a/497313/190597
    win = gtk.Window()
    win.set_default_size(300, 50)
    win.connect("destroy", gtk.main_quit)
    bar = ProgressBar()
    win.add(bar.scale)
    win.show_all()
    gtk.main()

demo_timeout_add()
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Can you tell me the gobject equivalent in GTK-3? – Manoj Aug 05 '12 at 21:07
  • 1
    According to [this tutorial](http://python-gtk-3-tutorial.readthedocs.org/en/latest/cellrenderers.html), `from gi.repository import GObject`, and then `GObject.timeout_add(...)`. – unutbu Aug 05 '12 at 21:15
  • Where exactly should I add gobject.timeout_add? Im still not getting it! – Manoj Aug 06 '12 at 12:30
  • @manoj: As you are building your gtk widgets, but before you call `gtk.main()` (to start the gtk event loop), you can call `gobject.timeout_add(...)` to say, "By the way, I want this function to be called every `N` milliseconds". You can stick it just about anywhere (as long as the callback function is already defined). I'm not sure this explanation is so clear, so I'm including a runnable example. – unutbu Aug 06 '12 at 18:02