如何在 Tkinter 的文字框中即時顯示 LaTeX?


Python Matplotlib 庫在需要視覺化資料點並繪製圖表和圖形以分析資料的地方很有用。假設我們想建立一個 Tkinter 應用程式,我們可以處理 LaTeX 語法。

LaTeX 語法用於準備科學文件,例如公式、科學符號、數學字元和標點符號。要準備應用程式,我們需要使用**matplotlib**和**TkAgg**(Tkinter 中 Matplotlib 的後端 API)模組。以下步驟用於構建應用程式函式和小部件,

  • 匯入所需的庫,例如 Matplotlib、Tkinter、Ttk(用於設定小部件樣式)、TkAgg 等。
  • 新增一個框架並在其中定義一個標籤和一個 Entry 小部件。
  • 使用 Matplotlib 中的**figure()**方法定義圖形的大小。此圖形可用於在畫布上繪製語法。
  • 現在,建立一個 Canvas 小部件,我們將在其中使用**TkAgg**定義我們的圖形。
  • 定義一個函式來獲取 Entry 小部件的內容並將文字轉換為使用 Matplotlib 中預定義函式(即**text()**)的圖形。
  • 將輸出顯示在畫布上,然後將 Return 或 Click 事件與該函式繫結。

示例

# Import required libraries
from tkinter import *
from tkinter import ttk
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

# Use TkAgg in the backend of tkinter application
matplotlib.use('TkAgg')

# Create an instance of tkinter frame
win = Tk()

# Set the size of the window
win.geometry("700x350")

# Set the title of the window
win.title("LaTex Viewer")

# Define a function to get the figure output
def graph(text):
   # Get the Entry Input
   tmptext = entry.get()
   tmptext = "$"+tmptext+"$"
   # Clear any previous Syntax from the figure
   wx.clear()
   wx.text(0.2, 0.6, tmptext, fontsize = 20)
   canvas.draw()
# Create a Frame object
frame = Frame(win)
frame.pack()
# Create an Entry widget
var = StringVar()
entry = Entry(frame, width=70, textvariable=var)
entry.pack()

# Add a label widget in the frame
label = Label(frame)
label.pack()

# Define the figure size and plot the figure
fig = matplotlib.figure.Figure(figsize=(7, 4), dpi=100)
wx = fig.add_subplot(111)
canvas = FigureCanvasTkAgg(fig, master=label)
canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1)

# Set the visibility of the Canvas figure
wx.get_xaxis().set_visible(False)
wx.get_yaxis().set_visible(False)

win.bind('<Return>', graph)
win.mainloop()

輸出

執行以上程式碼將顯示一個帶有 Entry 小部件和圖形圖的視窗。現在,鍵入一些科學表示式以顯示 LaTeX 格式的結果輸出。

更新於: 2021年6月8日

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.