ไลบรารี Python Matplotlib มีประโยชน์ในแอปพลิเคชันที่เราจำเป็นต้องแสดงจุดข้อมูลเป็นภาพและวาดกราฟและแปลงเพื่อวิเคราะห์ข้อมูล สมมติว่าเราต้องการสร้างแอปพลิเคชัน tkinter ซึ่งเราสามารถประมวลผลไวยากรณ์ LaTex ได้
ไวยากรณ์ LaTex ใช้สำหรับเตรียมเอกสารทางวิทยาศาสตร์ เช่น สูตร สัญลักษณ์ทางวิทยาศาสตร์ อักขระทางคณิตศาสตร์ และเครื่องหมายวรรคตอน เพื่อเตรียมใบสมัคร เราจำเป็นต้องใช้ matplotlib และ TkAgg (API แบ็กเอนด์สำหรับ Matplotlib ใน Tkinter) โมดูล ขั้นตอนต่อไปนี้ใช้เพื่อจัดโครงสร้างฟังก์ชันและวิดเจ็ตของแอปพลิเคชัน
- นำเข้าไลบรารีที่จำเป็น เช่น Matplotlib, Tkinter, Ttk (สำหรับการจัดรูปแบบวิดเจ็ต), TkAgg เป็นต้น
- เพิ่มเฟรมและกำหนดป้ายกำกับและวิดเจ็ตรายการ
- กำหนดขนาดของรูปโดยใช้ figure() วิธีการใน Matplotlib สามารถใช้ตัวเลขนี้เพื่อพล็อตไวยากรณ์ในแคนวาสได้
- ตอนนี้ สร้างวิดเจ็ต 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() ผลลัพธ์
การดำเนินการโค้ดข้างต้นจะแสดงหน้าต่างพร้อมวิดเจ็ตรายการและแผนภาพ ตอนนี้ พิมพ์นิพจน์ทางวิทยาศาสตร์เพื่อแสดงผลลัพธ์ในรูปแบบ LaTex
