Question

I know that matplotlib can render math expressions readily with, for instance,

txt=Text(x,y,r'$\frac{1}{2}')

which would make the fraction 1 over 2 at x,y. However, instead of placing the text at x,y I would like to use the rendered string in a separate tk application (like an Entry or Combobox). How can I obtain the rendered string from matplotlib's mathtext and put it into my tk widget? Of course I would welcome other options that would render the latex strings into my tk widget without matplotlib, but it seems like matplotlib has already done most of the work.

Was it helpful?

Solution

I couldn't really find that information in documentation, or net in general, but I was able to find solution by reading mathtext source code. That example is saving image to a file.

from matplotlib.mathtext import math_to_image
math_to_image("$\\alpha$", "alpha.png", dpi=1000, format='png')

You can always use ByteIO and use that buffer as a replace for image file, keeping data in memory. Or you can render directly from numpy array that is returned by data.as_array() in following code example (this code also uses cmap to control color of printed math expression).

from matplotlib.mathtext import MathTextParser
from matplotlib.image import imsave
parser =  MathTextParser('bitmap')
data, someint = parser.parse("$\\alpha$", dpi=1000)
imsave("alpha.png",data.as_array(),cmap='gray')

UPDATE

Here is complete TkInter example based on Hello World! example from Tkinter documentation, as requested. This one uses PIL library.

import tkinter as tk
from matplotlib.mathtext import math_to_image
from io import BytesIO
from PIL import ImageTk, Image

class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.pack()
        self.createWidgets()



    def createWidgets(self):

        #Creating buffer for storing image in memory
        buffer = BytesIO()

        #Writing png image with our rendered greek alpha to buffer
        math_to_image('$\\alpha$', buffer, dpi=1000, format='png')

        #Remoting bufeer to 0, so that we can read from it
        buffer.seek(0)

        # Creating Pillow image object from it
        pimage= Image.open(buffer)

        #Creating PhotoImage object from Pillow image object
        image = ImageTk.PhotoImage(pimage)

        #Creating label with our image
        self.label = tk.Label(self,image=image)

        #Storing reference to our image object so it's not garbage collected,
        # as TkInter doesn't store references by itself
        self.label.img = image

        self.label.pack(side="bottom")
        self.QUIT = tk.Button(self, text="QUIT", fg="red",
                                            command=root.destroy)
        self.QUIT.pack(side="top")

root = tk.Tk()
app = Application(master=root)
app.mainloop()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top