【问题标题】:Webkit threads with PyGObject on Gtk3在 Gtk3 上使用 PyGObject 的 Webkit 线程
【发布时间】:2012-06-17 09:28:25
【问题描述】:

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

我看到了例子PyGTK, Threads and 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 调用不起作用。唯一的工作部分是在主线程上注释的调用。

【问题讨论】:

    标签: python webkit pygtk gtk3 pygobject


    【解决方案1】:

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

    就像这样:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 2012-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多