PyGTK,线程和WebKit [英] PyGTK, Threads and WebKit

查看:109
本文介绍了PyGTK,线程和WebKit的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的PyGTK应用中,在按钮上单击我需要:

In my PyGTK app, on button click I need to:

  1. 获取一些html(可能需要一些时间)
  2. 在新窗口中显示

在获取html时,我想保持GUI的响应性,所以我决定在单独的线程中进行.我使用WebKit呈现html.

While fetching html, I want to keep GUI responsive, so I decided to do it in separate thread. I use WebKit to render html.

问题是当WebView位于单独的线程中时,我得到了空页面.

The problem is I get empty page in WebView when it is in separated thread.

这有效:

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

是因为 Webkit不是线程安全的.有什么解决方法吗?

Is it because webkit is not thread-safe. Is there any workaround for this?

推荐答案

根据我的经验,对于gtk,有时无法正常工作的事情之一就是在单独线程中更新窗口小部件.

According to my experience, one of the things that sometimes doesn't work as you expect with gtk is the update of widgets in separate threads.

要解决此问题,可以使用线程中的数据,并使用

To workaround this problem, you can work with the data in threads, and use glib.idle_add to schedule the update of the widget in the main thread once the data has been processed.

以下代码是适用于我的示例的更新版本(time.sleep用于模拟实际情况下获取html的延迟):

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

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

这篇关于PyGTK,线程和WebKit的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆