How to create an HTML File Viewer with WxPython

How to create an HTML File Viewer with WxPython

Although there are more complex and dedicated tools like CEF to offer support to display HTML data in a window, many UI frameworks offer the same feature as well, not so powerful, but it should basically work for most of the common features.

WxPython is not the exception as you can display some HTML data as well with the Html Window class. The purpose of this class is to display rich content pages (either local file or downloaded via HTTP protocol) in a window based on a subset of the HTML standard. The width of the window is constant - given in the constructor - and virtual height is changed dynamically depending on page size. The following example shows how to render raw HTML data in a new window or from a file:

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

Full example with a filepicker

In order to fully understand how the logic to render HTML files, you can increase the difficulty of the example by adding the system filepicker to choose a file to render in the viewer:

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 = wildcard,
            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()

Initially, you will get a frame with a single button that allows you to open the filepicker and select an HTML file. Once you select a file, a new frame will appear with the HTML viewer and the content of the selected html file.

Happy coding !

Become a more social person