Webkit threads with PyGObject on Gtk3

梦想与她 提交于 2020-01-13 09:31:52

问题


I am trying to load a webkit view on a different thread than main thread for gtk.

I see the example PyGTK, Threads and WebKit

I slightly modify for support PyGObject and 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()

The result it is a empty window and "after sleep" print is never executed. The idle_add call doesn't work. The only work part is the call commented on main thread.


回答1:


I need GLib.threads_init() before gdk's.

Just like this:

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()


来源:https://stackoverflow.com/questions/11070263/webkit-threads-with-pygobject-on-gtk3

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