如何使用wxPython将带有外部链接的HTML文件加载到CSS文件?

问题描述

我正在尝试使用wx.html.HtmlWindow加载HTML文件。 HTML文件链接到外部样式表(CSS)文件。 问题是HTML窗口仅显示纯HTML文件,没有样式(颜色,字体等)。 我该如何解决这个问题?

HTML代码

<html>
<head>
<title>Embedded Style Sample</title>
<link href="E:\pythonGUI\styles.css" rel="stylesheet" type="text/css"/></head>
<body>
<h1>Embedded Style Sample testing</h1>
<h2>Next Line</h2>
</body>
</html>

CSS代码

h1{
    color: #0000FF;
  }
  h2{
    color: #00CCFF;
  }

the Html file on browser

Python代码

import  wx 
import  wx.html
import  wx.html2 
  
class MyHtmlFrame(wx.Frame):
    def __init__(self,parent,title): 
        wx.Frame.__init__(
            self,-1,title,size = (600,400)
        )
        html = wx.html.HtmlWindow(self) 
        html.LoadPage("E:\\pythonGUI\\newtest.html") 

app = wx.App()  
frm = MyHtmlFrame(None,"Simple HTML File Viewer")  
frm.Show()  
app.MainLoop()

HTML文件显示在HTML窗口中:

the Html file show on HTML window

解决方法

如果您想要完整的HTML / CSS支持以及Javascript引擎,请考虑改用wx.html2.WebView

来自wxpython文档:

wx.html确实没有CSS支持,但确实支持 简单样式:您可以使用“文本对齐”,“宽度”,“垂直对齐”和 所有元素的“背景”,SPAN元素的“其他” 样式还可以识别:

color

font-family

font-size (only in point units)

font-style (only “oblique”,“italic” and “normal” values are supported)

font-weight (only “bold” and “normal” values are supported)

text-decoration (only “underline” value is supported)
,

使用wx.html2.WebView代替wx.html.HtmlWindow:

import wx
import wx.html2

class About(wx.Frame):
    def __init__(self):
        wx.Panel.__init__(self,None,-1,title="Title",size=(700,700))

class Test(wx.Frame):
    def __init__(self,title,pos,size):
        wx.Frame.__init__(self,size)
        self.tester=wx.html2.WebView.New(self)
        self.tester.LoadURL("E:\\pythonGUI\\newtest.html")

if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = Test("html2 web view",(20,20),(800,600))
    frame.Show()
    app.MainLoop()