尽管CEF等更复杂, 专用的工具提供了在窗口中显示HTML数据的支持, 但是许多UI框架也提供了相同的功能, 虽然功能不那么强大, 但是基本上可以用于大多数常见功能。
WxPython也不例外, 因为你可以使用Html Window类显示一些HTML数据。此类的目的是在基于HTML标准子集的窗口中显示丰富的内容页面(本地文件或通过HTTP协议下载)。窗口的宽度是恒定的(在构造函数中指定), 并且虚拟高度会根据页面大小动态更改。以下示例显示了如何在新窗口或文件中呈现原始HTML数据:
import wx
import wx.html
class MyHtmlFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(
self, parent, -1, title, size = (600, 400)
)
# Use current window as container of the Html Frame
html = wx.html.HtmlWindow(self)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
# Alternatively render raw HTML with the SetPage method
# html.SetPage("<h4>Hello World</h4>")
# Render a local HTML file
html.LoadPage("C:\\Users\\sdkca\\Desktop\\python-sandbox\\index.html")
app = wx.App()
frm = MyHtmlFrame(None, "Simple HTML File Viewer")
frm.Show()
app.MainLoop()
带有文件选择器的完整示例
为了完全理解呈现HTML文件的逻辑, 你可以通过添加系统文件选择器以选择要在查看器中呈现的文件来增加示例的难度:
import os
import wx
import wx.html
FileFilter = "Html files (*.html)|*.html|" \
"All files (*.*)|*.*"
class MyApp(wx.Frame):
# ----------------------------------------------------------------------
def __init__(self):
wx.Frame.__init__(self, None, wx.ID_ANY, "HTML Viewer with File picker"
)
# Create a panel within the frame
panel = wx.Panel(self, wx.ID_ANY)
self.currentDirectory = os.getcwd()
# Create the filepicker button and add the 'onOpenFile' binding
openFileDlgBtn = wx.Button(
panel, label = "Choose an HTML File"
)
openFileDlgBtn.Bind(wx.EVT_BUTTON, self.onOpenFile)
# Put the button in a sizer
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(openFileDlgBtn, 0, wx.ALL|wx.CENTER, 5)
panel.SetSizer(sizer)
# ----------------------------------------------------------------------
"""
Create and show the Open FileDialog
"""
def onOpenFile(self, event):
dlg = wx.FileDialog(
self, message = "Choose a file", defaultDir = self.currentDirectory, defaultFile = "", wildcard = FileFilter, style = wx.FD_OPEN | wx.FD_CHANGE_DIR
)
## If the user selects a file, open it in the Html File Viewer
if dlg.ShowModal() == wx.ID_OK:
htmlFilePath = dlg.GetPath()
# Create a new instance of the HtmlViewer
htmlViewerInstance = HtmlViewer(None, htmlFilePath)
htmlViewerInstance.Show()
dlg.Destroy()
# The HtmlViewer class expects the path of the HTML file
# to open it in a new window of the HtmlWindow type
class HtmlViewer(wx.Frame):
def __init__(self, parent, filepath):
wx.Frame.__init__(
self, parent, -1, "HTML Viewer", size = (800, 600)
)
# Open a new HtmlWindow that is capable of rendering such content
html = wx.html.HtmlWindow(self)
self.Maximize(True)
if "gtk2" in wx.PlatformInfo:
html.SetStandardFonts()
# Load the selected file in the viewer !
html.LoadPage(filepath)
# Run the program !
if __name__ == "__main__":
app = wx.App(False)
frame = MyApp()
frame.Show()
app.MainLoop()
最初, 你将获得一个带有单个按钮的框架, 该按钮使你可以打开文件选择器并选择一个HTML文件。选择文件后, HTML查看器和所选html文件的内容将出现一个新框架。
编码愉快!
评论前必须登录!
注册