2012-06-17 44 views
6

我試圖在不同於gtk主線程的線程上加載webkit視圖。在Gtk3上使用PyGObject的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調用不起作用。唯一的工作部分是對主線程的評論。

回答

6

我需要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()