Use wxPython and ECharts to generate and save HTML charts

Use wxPython and ECharts library to generate and save HTML charts. wxPython is a Python GUI library based on wxWidgets, while ECharts is a JavaScript library for data visualization.
C:\pythoncode\blog\echartshow.py
insert image description here
Reference URL: https://echarts.apache.org/v4/examples/zh/index.html

install dependencies

Before we start, we need to make sure that the necessary dependencies are installed. You can use the following commands to install wxPython and ECharts libraries:

pip install wxPython

Create application window

First, let's create an application window that will serve as an interface for chart generation and saving.

import wx
import wx.html2 as webview

class MainFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="HTML Viewer", size=(800, 600))
        self.panel = wx.Panel(self)

        # 创建GUI组件
        self.echart_memo = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
        self.button_generate = wx.Button(self.panel, label="生成")
        self.button_save = wx.Button(self.panel, label="保存")
        self.web = None

        # 绑定事件处理函数
        self.button_generate.Bind(wx.EVT_BUTTON, self.on_generate)
        self.button_save.Bind(wx.EVT_BUTTON, self.on_save)

        # 创建布局
        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.echart_memo, proportion=1, flag=wx.EXPAND)
        sizer.Add(self.button_generate, flag=wx.EXPAND)
        sizer.Add(self.button_save, flag=wx.EXPAND)

        self.panel.SetSizer(sizer)

In the above code, we created a class called MainFrame which inherits from wx.Frame. In the constructor, we create text boxes for entering ECharts options, buttons for generating and saving charts, and add them to a panel with a vertical layout.

Generate and save diagrams

Next, we'll implement the functionality to generate and save the graph.

    def on_generate(self, event):
        echart_options = self.echart_memo.GetValue()

        if self.web is not None:
            self.web.Destroy()

        self.web = webview.WebView.New(self.panel, -1, parent=self.panel, style=wx.NO_BORDER)
        sizer = self.panel.GetSizer()
        sizer.Add(self.web, proportion=1, flag=wx.EXPAND)
        self.panel.Layout()

        # 构建完整的HTML文件
        html = f'''
        <html>
        <head>
            <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
            <script type="text/javascript">
                var chartDom = document.getElementById('echart-container');
                var myChart = echarts.init(chartDom);
                var option = {
      
      echart_options};
                myChart.setOption(option);
            </script>
        </head>
        <body>
            <div id="echart-container" style="width: 100%; height: 400px;"></div>
        </body>
        </html>
        '''

        self.web.SetPage(html, "")

    def on_save(self, event):
        echart_options = self.echart_memo.GetValue()

        # 构建完整的HTML文件
        html = f'''
        <html>
        <head>
            <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>
            <script type="text/javascript">
                var chartDom = document.getElementById('echart-container');
                var myChart = echarts.init(chartDom);
                var option = {
      
      echart_options};
                myChart.setOption(option);
            </script>
        </head>
        <body>
            <div id="echart-container" style="width: 100%; height: 400px;"></div>
        </body>
        </html>
        '''

        # 保存HTML文件
        current_datetime = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        file_path = f"./html/{
      
      current_datetime}.html"
        with open(file_path, "w") as file:
            file.write(html)

        wx.MessageBox(f"保存成功!文件路径:{
      
      file_path}", "保存成功", wx.OK | wx.ICON_INFORMATION)

In the above code, we defined on_generateand on_savetwo methods. on_generateThe method is called when the user clicks the "Generate" button, it gets the ECharts options from the text box, and dynamically generates the HTML string containing the chart according to the options. We then use the wxWebView component to load the HTML string into the application window to display the resulting chart.

on_saveThe method is called when the user clicks the "Save" button. It is on_generatesimilar to the method, but also saves the generated HTML string as an HTML file. Filenames use the current timestamp to ensure each file has a unique name. After the save is successful, we use wx.MessageBox to display a message box to notify the user that the save operation was successful and display the saved file path.

run the application

Finally, we create a wx.App instance, instantiate the MainFrame class, and run the application's event loop.

if __name__ == "__main__":
    app = wx.App()
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

The above code snippet creates a wx.App instance and initializes the application's GUI. We then show the main window and app.MainLoop()start the application's event loop by calling a method, keeping the application running.
Full code:

import wx
import wx.html2 as webview
import datetime


class MainFrame(wx.Frame):
    def __init__(self):
        super().__init__(None, title="HTML Viewer", size=(800, 600))
        self.panel = wx.Panel(self)

        self.echart_memo = wx.TextCtrl(self.panel, style=wx.TE_MULTILINE)
        self.button_generate = wx.Button(self.panel, label="生成")
        self.button_save = wx.Button(self.panel, label="保存")
        self.web = webview.WebView.New(self.panel)

        self.button_generate.Bind(wx.EVT_BUTTON, self.on_generate)
        self.button_save.Bind(wx.EVT_BUTTON, self.on_save)

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(self.echart_memo, proportion=1, flag=wx.EXPAND)
        sizer.Add(self.button_generate, flag=wx.EXPAND)
        sizer.Add(self.button_save, flag=wx.EXPAND)
        sizer.Add(self.web, proportion=1, flag=wx.EXPAND)

        self.panel.SetSizer(sizer)

    def on_generate(self, event):
        echart_options = self.echart_memo.GetValue()

        # 构建完整的HTML文件
        html = f'''
         <html>
        <head>
            <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>

        </head>
        <body>
            <div id="chart-container" style="width: 100%; height: 400px;"></div>
                        <script>              
                var chart = echarts.init(document.getElementById('chart-container'));
                var  {
      
      echart_options}
                chart.setOption(option);
            </script>
        </body>
        </html>
        '''

        self.web.SetPage(html, "")

    def on_save(self, event):
        echart_options = self.echart_memo.GetValue()

        # 构建完整的HTML文件
        # html = f'''
        html = f'''
         <html>
        <head>
            <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js"></script>

        </head>
        <body>
            <div id="chart-container" style="width: 100%; height: 400px;"></div>
                        <script>              
                var chart = echarts.init(document.getElementById('chart-container'));
                var  {
      
      echart_options}
                chart.setOption(option);
            </script>
        </body>
        </html>
        '''

        # 保存HTML文件
        current_datetime = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        file_path = f"../html/{
      
      current_datetime}.html"
        with open(file_path, "w") as file:
            file.write(html)

        wx.MessageBox(f"保存成功!文件路径:{
      
      file_path}", "保存成功", wx.OK | wx.ICON_INFORMATION)


if __name__ == '__main__':
    app = wx.App()
    frame = MainFrame()
    frame.Show()
    app.MainLoop()

in conclusion

This blog introduces how to use wxPython and ECharts library to generate and save HTML charts. By combining the GUI components of wxPython and the data visualization functions of ECharts, we can easily create a chart generation and saving tool. Users only need to enter the ECharts option, click the generate button to view the chart in the application window in real time, and can save the chart as an HTML file for further use.

Guess you like

Origin blog.csdn.net/winniezhang/article/details/132332428