7

我正在尝试在与 gtk 的主线程不同的线程上加载 webkit 视图。

我看到了PyGTK、Threads 和 WebKit的例子

我稍微修改一下以支持 PyGObject 和 GTK3:

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import GLib
from gi.repository import WebKit
import threading
import time

# Use threads                                       
Gdk.threads_init()

class App(object):
    def __init__(self):
        window = Gtk.Window()
        webView = WebKit.WebView()
        window.add(webView)
        window.show_all()

        #webView.load_uri('http://www.google.com') # Here it works on main thread

        self.window = window
        self.webView = webView

    def run(self):
        Gtk.main()

    def show_html(self):
        print 'show html'

        time.sleep(1)
        print 'after sleep'

        # Update widget in main thread             
        GLib.idle_add(self.webView.load_uri, 'http://www.google.com') # Here it doesn't work

app = App()

thread = threading.Thread(target=app.show_html)
thread.start()

app.run()
Gtk.main()

结果是一个空窗口,并且永远不会执行“睡眠后”打印。idle_add 调用不起作用。唯一的工作部分是在主线程上注释的调用。

4

1 回答 1

6

我需要 GLib.threads_init() 在 gdk 之前。

像这样:

from gi.repository import Gtk
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import GLib
from gi.repository import WebKit
import threading
import time

# Use threads                                       
GLib.threads_init()

class App(object):
    def __init__(self):
        window = Gtk.Window()
        webView = WebKit.WebView()
        window.add(webView)
        window.show_all()

        #webView.load_uri('http://www.google.com') # Here it works on main thread

        self.window = window
        self.webView = webView

    def run(self):
        Gtk.main()

    def show_html(self):
        print 'show html'

        time.sleep(1)
        print 'after sleep'

        # Update widget in main thread             
        GLib.idle_add(self.webView.load_uri, 'http://www.google.com') # Here it doesn't work

app = App()

thread = threading.Thread(target=app.show_html)
thread.start()

app.run()
Gtk.main()
于 2012-06-17T09:58:39.553 回答