python - Gtk3 上带有 PyGObject 的 Webkit 线程

标签 python webkit pygtk gtk3 pygobject

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

我看到了例子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()

结果是一个空窗口,“ sleep 后”打印永远不会执行。 idle_add 调用不起作用。唯一的工作部分是在主线程上注释的调用。

最佳答案

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

关于python - Gtk3 上带有 PyGObject 的 Webkit 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11070263/

相关文章:

python - 在 session 提交时更改对象的属性 - Flask SQLAlchemy

python - 如何同时过滤多个值?

css - 如何使 CSS 兼容所有浏览器?

javascript - iPhone Safari Web 应用程序 : Seeking overview of iPhone-specific features

python - Msys2 上的 Pyinstaller 与 pygobject

python - 如何消除棋盘伪影

python - 在两列上分组并使用 pandas - Python 在特定列上应用转换(分区)、滚动和连接

java - Python或Java模块在服务器端渲染HTML页面并获取DOM对象

python - gtk.ScrolledWindow 具有 gtk.TextView 显示固定的第一行

python - pygtk 仅在一个 pixbuf 中加载图像流