Steven Sproat 走在了正确的轨道上(感谢您让我参与其中 - 没有您的建议就无法做到) - 以下是完整解决方案的相关部分:
import wx.html as html
import urllib2 as urllib2
import os
import tempfile
import threading
from Queue import Queue
class HTTPThread(threading.Thread):
def __init__(self, urlQueue, responseQueue):
threading.Thread.__init__(self)
self.urlQueue = urlQueue
self.responseQueue = responseQueue
def run(self):
# add error handling
url = self.urlQueue.get()
request = urllib2.Request(url)
response = urllib2.urlopen(request)
page = response.read()
self.responseQueue.put(page)
在您的 html.HtmlWindow 派生类中:
def OnOpeningURL(self, type, url):
if type == html.HTML_URL_IMAGE:
# If it is a tempfile already, just tell it to open it.
# Since it will be called again
# immediately after first failure only need to keep the last
# temp file within the object, and the former is closed!
if self.f is not None and self.f.name in url:
return html.HTML_OPEN
# if its not a tempfile, download asynchronously and redirect
urlq = Queue()
resq = Queue()
t = HTTPThread(urlq, resq)
t.start()
urlq.put_nowait(url)
while True:
if resq.empty():
# your task while waiting
time.sleep(0.1)
else:
img = resq.get()
break
self.f = tempfile.NamedTemporaryFile()
self.f.write(img)
self.f.seek(0)
return 'file://' + self.f.name
else:
return html.HTML_OPEN
对于我的应用程序来说,这很好用,但如果你真的想让图像加载“像普通的网络浏览器一样”,那么你需要的不仅仅是 wx.html.HtmlWindow。但是,这是非阻塞的,并且会正确加载图像。