首页 > 解决方案 > wxpython - create a wx.html.HtmlWindow() that has highlighted text

问题描述

Using wxpython 4.1.0, Windows 10 x64, Python 3.7.7 x64...

What I want to achieve is pretty basic, but cannot figure it out from reading wxpython documentation and searching the internet.

I used python's native difflib module to create an HTML difference report. If you open this html difference report using any popular browser, Chrome, Firefox, Edge, and etc. you get nice highlighting that distinguishes the differences that were found.

When I open this same file using wxpythons wx.html.HtmlWindow() widget, the nice visuals are not shown. The highlighting that clearly shows the differences is not displayed and instead just text is displayed making it nearly impossible to find the differences.

wxpython is very complete in terms of functionality and I assume there is a way to achieve this using the wx.html.HtmlWindow() widget or a similar widget(s) in the wx.html API. I'm thinking the only way of achieving this is maybe using the wx.html2 API.

Minimal amount of code to view my problem (not including in classes for simplicity):

DIFFLIB Code:

import difflib
import pathlib as path


file1 = path.Path('text_file1.txt')
file2 = path.Path('text_file2.txt')

with file1.open() as file_obj1:
    contents1 = file_obj1.readlines()

with file2.open() as file_obj2:
    contents2 = file_obj2.readlines()

html = difflib.HtmlDiff().make_file(contents1, contents2, file1.name, file2.name)

with open('report.html', 'w') as file_obj:
    file_obj.write(html)

GUI Code:

import wx
import wx.html    
        
def html_window():
    frame = wx.Frame(parent=None)
    html = wx.html.HtmlWindow(frame)
    html.LoadFile('report.html')
    frame.Show()

    
app = wx.App(False)
html_window()
app.MainLoop()

标签: pythonhtmlwxpythonreportdifflib

解决方案


Your problem lies with wx.html not supporting css.
wx.html2 does but even that may struggle with inline css which is what you have in the report.html file.
Still, you could always try wx.html2.
Other than that, why not use wx.LaunchDefaultBrowser("path_to_file/report.html")

One other option that springs to mind, is use:

difflib.HtmlDiff().make_table(contents1, contents2, file1.name, file2.name)

and then add your own css.


推荐阅读