How to use matplotlib to display mathtext outside matplotlib in another tk widget?

I know that matplotlib can easily display math expressions like

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

what would make fraction 1 over 2 at x, y. However, instead of placing the text in x, y, I would like to use the displayed string in a separate tk application (e.g. Entry or Combobox). How to get the received string from matplotlib mathtext and put it in my tk widget? Of course, I would welcome other options that will make latex strings in my tk widgets without matplotlib, but it looks like matplotlib has already done most of the work.

+3
source share
1 answer

, , mathtext. - .

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

ByteIO , . numpy, data.as_array() ( cmap ).

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

TkInter Hello World! Tkinter . PIL.

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 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()
+1

Source: https://habr.com/ru/post/1653958/


All Articles