{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\n# Display mathtext in WX\n\nDemonstrates how to convert (math)text to a wx.Bitmap for display in various\ncontrols on wxPython.\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "collapsed": false
      },
      "outputs": [],
      "source": [
        "from io import BytesIO\n\nimport wx\n\nimport numpy as np\n\nfrom matplotlib.backends.backend_wx import NavigationToolbar2Wx\nfrom matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas\nfrom matplotlib.figure import Figure\n\nIS_WIN = 'wxMSW' in wx.PlatformInfo\n\n\ndef mathtext_to_wxbitmap(s):\n    # We draw the text at position (0, 0) but then rely on\n    # ``facecolor=\"none\"`` and ``bbox_inches=\"tight\", pad_inches=0`` to get a\n    # transparent mask that is then loaded into a wx.Bitmap.\n    fig = Figure(facecolor=\"none\")\n    text_color = (\n        np.array(wx.SystemSettings.GetColour(wx.SYS_COLOUR_WINDOWTEXT)) / 255)\n    fig.text(0, 0, s, fontsize=10, color=text_color)\n    buf = BytesIO()\n    fig.savefig(buf, format=\"png\", dpi=150, bbox_inches=\"tight\", pad_inches=0)\n    s = buf.getvalue()\n    return wx.Bitmap.NewFromPNGData(s, len(s))\n\n\nfunctions = [\n    (r'$\\sin(2 \\pi x)$', lambda x: np.sin(2*np.pi*x)),\n    (r'$\\frac{4}{3}\\pi x^3$', lambda x: (4/3)*np.pi*x**3),\n    (r'$\\cos(2 \\pi x)$', lambda x: np.cos(2*np.pi*x)),\n    (r'$\\log(x)$', lambda x: np.log(x))\n]\n\n\nclass CanvasFrame(wx.Frame):\n    def __init__(self, parent, title):\n        super().__init__(parent, -1, title, size=(550, 350))\n\n        self.figure = Figure()\n        self.axes = self.figure.add_subplot()\n\n        self.canvas = FigureCanvas(self, -1, self.figure)\n\n        self.change_plot(0)\n\n        self.sizer = wx.BoxSizer(wx.VERTICAL)\n        self.add_buttonbar()\n        self.sizer.Add(self.canvas, 1, wx.LEFT | wx.TOP | wx.GROW)\n        self.add_toolbar()  # comment this out for no toolbar\n\n        menuBar = wx.MenuBar()\n\n        # File Menu\n        menu = wx.Menu()\n        m_exit = menu.Append(\n            wx.ID_EXIT, \"E&xit\\tAlt-X\", \"Exit this simple sample\")\n        menuBar.Append(menu, \"&File\")\n        self.Bind(wx.EVT_MENU, self.OnClose, m_exit)\n\n        if IS_WIN:\n            # Equation Menu\n            menu = wx.Menu()\n            for i, (mt, func) in enumerate(functions):\n                bm = mathtext_to_wxbitmap(mt)\n                item = wx.MenuItem(menu, 1000 + i, \" \")\n                item.SetBitmap(bm)\n                menu.Append(item)\n                self.Bind(wx.EVT_MENU, self.OnChangePlot, item)\n            menuBar.Append(menu, \"&Functions\")\n\n        self.SetMenuBar(menuBar)\n\n        self.SetSizer(self.sizer)\n        self.Fit()\n\n    def add_buttonbar(self):\n        self.button_bar = wx.Panel(self)\n        self.button_bar_sizer = wx.BoxSizer(wx.HORIZONTAL)\n        self.sizer.Add(self.button_bar, 0, wx.LEFT | wx.TOP | wx.GROW)\n\n        for i, (mt, func) in enumerate(functions):\n            bm = mathtext_to_wxbitmap(mt)\n            button = wx.BitmapButton(self.button_bar, 1000 + i, bm)\n            self.button_bar_sizer.Add(button, 1, wx.GROW)\n            self.Bind(wx.EVT_BUTTON, self.OnChangePlot, button)\n\n        self.button_bar.SetSizer(self.button_bar_sizer)\n\n    def add_toolbar(self):\n        \"\"\"Copied verbatim from embedding_wx2.py\"\"\"\n        self.toolbar = NavigationToolbar2Wx(self.canvas)\n        self.toolbar.Realize()\n        # By adding toolbar in sizer, we are able to put it at the bottom\n        # of the frame - so appearance is closer to GTK version.\n        self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)\n        # update the axes menu on the toolbar\n        self.toolbar.update()\n\n    def OnChangePlot(self, event):\n        self.change_plot(event.GetId() - 1000)\n\n    def change_plot(self, plot_number):\n        t = np.arange(1.0, 3.0, 0.01)\n        s = functions[plot_number][1](t)\n        self.axes.clear()\n        self.axes.plot(t, s)\n        self.canvas.draw()\n\n    def OnClose(self, event):\n        self.Destroy()\n\n\nclass MyApp(wx.App):\n    def OnInit(self):\n        frame = CanvasFrame(None, \"wxPython mathtext demo app\")\n        self.SetTopWindow(frame)\n        frame.Show(True)\n        return True\n\n\nif __name__ == \"__main__\":\n    app = MyApp()\n    app.MainLoop()"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.14.7"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}