还有一个使用sympy的解决方案。它的部分灵感来自对this subreddit 的回答。特别是它使用sympy.printing.preview 方法。
这是导入部分
#!/usr/bin/python3
from tkinter import *
import sympy as sp
from PIL import Image, ImageTk
from io import BytesIO
然后我定义了 GUI,非常标准的东西。我没有花太多力气
class Root():
def __init__(self, master):
#Define the main window and the relevant widgets
self.master = master
master.geometry("800x300")
self.strvar = StringVar()
self.label = Label(master)
self.entry = Entry(master, textvariable = self.strvar, width = 80)
self.button = Button(text = "LaTeX!", command = self.on_latex)
#The Euler product formula
self.strvar.set("\prod_{p\,\mathrm{prime}}\\frac1{1-p^{-s}} = \sum_{n=1}^\infty \\frac1{n^s}")
#Pack everything
self.entry.pack()
self.button.pack()
self.label.pack()
然后我们定义渲染LaTeX的函数(保持缩进)
def on_latex(self):
expr = "$\displaystyle " + self.strvar.get() + "$"
#This creates a ByteIO stream and saves there the output of sympy.preview
f = BytesIO()
the_color = "{" + self.master.cget('bg')[1:].upper()+"}"
sp.preview(expr, euler = False, preamble = r"\documentclass{standalone}"
r"\usepackage{pagecolor}"
r"\definecolor{graybg}{HTML}" + the_color +
r"\pagecolor{graybg}"
r"\begin{document}",
viewer = "BytesIO", output = "ps", outputbuffer=f)
f.seek(0)
#Open the image as if it were a file. This works only for .ps!
img = Image.open(f)
#See note at the bottom
img.load(scale = 10)
img = img.resize((int(img.size[0]/2),int(img.size[1]/2)),Image.BILINEAR)
photo = ImageTk.PhotoImage(img)
self.label.config(image = photo)
self.label.image = photo
f.close()
我选择文档类standalone 是为了使生成的文档的大小适应其内容。然后我使用包pagecolor 使页面与背景无缝融合。另请注意,PIL 与每个format 都不兼容。例如,选择 .pdf 的输出会在定义 img 时产生错误,而选择 .png 会在定义 photo 时产生问题。 .ps 格式效果很好,而且它也是矢量的,这很好。
终于有人需要了
master = Tk()
root = Root(master)
master.mainloop()
这就是它的样子
注意:
在那里,我将图片放大了 10 倍,然后将其缩小了 1/2。这只是因为它看起来更平滑和更好,但它不是必需的。第一次缩放使用 .ps 格式的矢量特性,因此不会丢失分辨率,而第二次缩放作用于光栅化图像。