下面是从我的一个 gtk 应用程序中截取的线程示例。这可能会有所帮助。
#!/usr/bin/env python3
# Copyright (C) 2013 LiuLang <gsushzhsosgsu@gmail.com>
# Use of this source code is governed by GPLv3 license that can be found
# in http://www.gnu.org/licenses/gpl-3.0.html
from gi.repository import GObject
from gi.repository import Gtk
import threading
#UPDATE_INTERVAL = 6 * 60 * 60 * 1000 # 6 hours
UPDATE_INTERVAL = 2 * 1000 # 2 secs, for test only
def async_call(func, func_done, *args):
'''
Call func in another thread, without blocking gtk main loop.
`func` does time-consuming job in background, like access website.
If `func_done` is not None, it will be called after func() ends.
func_done is called in gtk main thread, and this function is often used
to update GUI widgets in app.
`args` are parameters for func()
'''
def do_call(*args):
result = None
error = None
try:
result = func(*args)
except Exception as e:
error = e
if func_done is not None:
GObject.idle_add(lambda: func_done(result, error))
thread = threading.Thread(target=do_call, args=args)
thread.start()
class App(Gtk.Window):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.set_default_size(480, 320)
self.set_border_width(5)
self.set_title('Gtk Threads')
self.connect('delete-event', self.on_app_exit)
self.update_timer = GObject.timeout_add(UPDATE_INTERVAL,
self.check_update)
def run(self):
self.show_all()
Gtk.main()
def on_app_exit(self, *args):
Gtk.main_quit()
def check_update(self):
def _do_check_update():
print('do check update: will check for updating info')
print(threading.current_thread(), '\n')
print('check update')
print(threading.current_thread())
async_call(_do_check_update, None)
return True
if __name__ == '__main__':
app = App()
app.run()