Periodically call a function in pygtk's main loop

跟風遠走 提交于 2019-12-21 04:34:14

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!