PyGTK, Threads and WebKit

In my PyGTK application, when I click a button, I need:

  • Get some html (may take some time)
  • Show in new window

When extracting html, I want the GUI to respond, so I decided to do this in a separate thread. I am using WebKit for html rendering.

The problem is that I get a blank page in the WebView when it is in a separate branch.

It works:

import gtk import webkit webView = webkit.WebView() webView.load_html_string('<h1>Hello Mars</h1>', 'file:///') window = gtk.Window() window.add(webView) window.show_all() gtk.mainloop() 

This does not work, creates an empty window:

 import gtk import webkit import threading def show_html(): webView = webkit.WebView() webView.load_html_string('<h1>Hello Mars</h1>', 'file:///') window = gtk.Window() window.add(webView) window.show_all() thread = threading.Thread(target=show_html) thread.setDaemon(True) thread.start() gtk.mainloop() 

This is because webkit is not thread safe . Is there a workaround for this?

+2
source share
2 answers

In my experience, one of the things that sometimes don't work as you expect with gtk is updating widgets in separate threads.

To work around this problem, you can work with data in streams and use glib.idle_add to schedule widget updates to the main stream after data processing.

The following code is an updated version of your example that works for me ( time.sleep used to simulate the delay in receiving html in a real script):

 import gtk, glib import webkit import threading import time # Use threads gtk.gdk.threads_init() class App(object): def __init__(self): window = gtk.Window() webView = webkit.WebView() window.add(webView) window.show_all() self.window = window self.webView = webView def run(self): gtk.main() def show_html(self): # Get your html string time.sleep(3) html_str = '<h1>Hello Mars</h1>' # Update widget in main thread glib.idle_add(self.webView.load_html_string, html_str, 'file:///') app = App() thread = threading.Thread(target=app.show_html) thread.start() app.run() gtk.main() 
+3
source

I don't know anything about the internal workings of webkit, but maybe you can try it with several processes.

0
source

Source: https://habr.com/ru/post/918278/


All Articles