Is it possible for Python to display LaTex in real time in a text box?

后端 未结 4 2078
孤独总比滥情好
孤独总比滥情好 2020-12-28 22:47

I plan on making a GUI where the user would input their mathematical expressions into a text box, such as Tkinter Entry Widget, and their expressions would be displayed in t

4条回答
  •  被撕碎了的回忆
    2020-12-28 23:10

    This is a working example (python2, raspbian), although it is not very elegant. This is one solution among a multitude, but it shows all the steps from the latex source file to the Tkinter program.

    from subprocess import call
    import Tkinter
    
    TEX = (  # use raw strings for backslash
      r"\documentclass{article}",
      r"\begin{document}",
      r"$$a^2 + b^2 = c^2$$",
      r"$$x=\frac{-b \pm \sqrt{b^2 - 4ac}}{2a}$$",
      r"\end{document}",
    )
    
    with open('doc1.tex','w') as out_file:
      for t in TEX:
        out_file.write("%s\n" % t)
    
    call(['latex','doc1.tex'])
    call(['dvips','doc1.dvi','-o','doc1.ps'])
    call(['gs','-sDEVICE=ppmraw','-dNOPAUSE','-dBATCH','-dSAFER','-sOutputFile=doc1.ppm','doc1.ps'])
    
    root1 = Tkinter.Tk()
    img1 = Tkinter.PhotoImage(file="doc1.ppm")
    label1 = Tkinter.Label(root1, image=img1)
    label1.pack()
    root1.mainloop()
    

    There are a lot of possible variations: compile latex to pdf instead of ps; use other image file formats; use library PIL to support other formats, etc.

    This solution is also very inefficient (don't tell me, I know). For example, on my system, the ppm file is 1,5Mb. The equations also appear in the middle of a big page (it would need to be cropped).

    Even if it needs improvement, it answers your question (display a LaTeX document in a Tkinter program) and should give you a starting point.

提交回复
热议问题