问题
What's the pygtk equivalent for after method in tkinter?
I want to periodically call a function in the main loop.
What is the better way to achieve it?
回答1:
Use gobject.timeout_add:
import gobject
gobject.timeout_add(milliseconds, callback)
For example here is a progress bar that uses timeout_add
to update the progress (HScale
) value:
import gobject
import gtk
class Bar(object):
def __init__(self,widget):
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)
widget.add(self.scale)
gobject.timeout_add(100, self.timeout)
def timeout(self):
self.val +=1
self.scale.set_value(self.val)
return True
if __name__=='__main__':
win = gtk.Window()
win.set_default_size(300,50)
win.connect("destroy", gtk.main_quit)
bar=Bar(win)
win.show_all()
gtk.main()
回答2:
If you're using the new Python GObject Introspection API, you should use GLib.timeout_add().
Note that the documentation seems to be incorrect. It is actually:
timeout_add(interval, function, *user_data, **kwargs)
Here's an example. Note that run
is a callable object, but it could be any ordinary function or method.
from gi.repository import GLib
class Runner:
def __init__(self, num_times):
self.num_times = num_times
self.count = 0
def __call__(self, *args):
self.count += 1
print("Periodic timer [{}]: args={}".format(self.count, args))
return self.count < self.num_times
run = Runner(5)
interval_ms = 1000
GLib.timeout_add(interval_ms, run, 'foo', 123)
loop = GLib.MainLoop()
loop.run()
Output:
$ python3 glib_timeout.py
Periodic timer [1]: args=('foo', 123)
Periodic timer [2]: args=('foo', 123)
Periodic timer [3]: args=('foo', 123)
Periodic timer [4]: args=('foo', 123)
Periodic timer [5]: args=('foo', 123)
<messages stop but main loop keeps running>
来源:https://stackoverflow.com/questions/7309782/periodically-call-a-function-in-pygtks-main-loop