How Can I Use Matplotlib's Mathtext Rendering Outside Of Matplotlib In Another Tk Widget?
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 pl
Solution 1:
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.mathtextimportMathTextParserfrom matplotlib.imageimport 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
classApplication(tk.Frame):
def__init__(self, master=None):
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
defcreateWidgets(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()
Post a Comment for "How Can I Use Matplotlib's Mathtext Rendering Outside Of Matplotlib In Another Tk Widget?"