繁体   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