问题
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?
回答1:
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()
来源:https://stackoverflow.com/questions/11819952/how-to-display-continuous-data-in-a-py-gtk-window