簡體   English   中英

如何在另一個tk小部件中使用matplotlib在matplotlib之外的mathtext渲染?

[英]How can I use matplotlib's mathtext rendering outside of matplotlib in another tk widget?

我知道matplotlib可以很容易地渲染數學表達式,例如,

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

這將使分數1在x,y處超過2。 但是,我不想將文本放在x,y,而是想在單獨的tk應用程序(如Entry或Combobox)中使用渲染的字符串。 如何從matplotlib的mathtext中獲取渲染的字符串並將其放入我的tk小部件中? 當然我會歡迎其他選項,如果沒有matplotlib將乳膠字符串渲染到我的tk小部件中,但似乎matplotlib已經完成了大部分工作。

我無法在文檔或網絡中找到這些信息,但我能夠通過閱讀mathtext源代碼找到解決方案。 該示例將圖像保存到文件。

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

您始終可以使用ByteIO並使用該緩沖區替換圖像文件,將數據保存在內存中。 或者,您可以直接從以下代碼示例中的data.as_array()返回的numpy數組進行渲染(此代碼也使用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

這是基於Hello World的完整TkInter示例! 根據要求,來自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'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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM