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

4
我知道matplotlib可以轻松渲染数学表达式,例如:
txt=Text(x,y,r'$\frac{1}{2}')

将分数1/2放在x,y处。但是,我想在单独的tk应用程序(例如Entry或Combobox)中使用渲染后的字符串,而不是将文本放在x,y处。如何从matplotlib的mathtext获取渲染后的字符串并将其放入我的tk部件中?当然,如果有其他选项可以在没有matplotlib的情况下将latex字符串呈现到我的tk widget中,我也欢迎。但似乎matplotlib已经完成了大部分工作。


那不是它设计的用例。看看backend_tk中画布的工作方式。 - tacaswell
1个回答

3

我在文档或网上没有找到这个信息,但通过阅读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')

更新

这里是一个完整的TkInter示例,基于Tkinter文档中的Hello World! 示例,并使用了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()

1
谢谢您的回答。我相信这回答了如何从matplotlib中获取渲染文本的部分问题。您能否进一步详细说明如何在Tk中使用该输出图像? - esmit
@esmit 我已经更新了我的答案,并提供了完整的TkInter示例。 - lyuden

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接