ไลบรารี Python Matplotlib มีประโยชน์ในหลาย ๆ แอพพลิเคชั่นสำหรับการแสดงข้อมูลและสารสนเทศที่ให้มาในรูปของกราฟและพล็อต เป็นไปได้ที่จะเรียกใช้ matplotlib ในแอปพลิเคชัน Tkinter โดยทั่วไป การนำเข้าไลบรารี Python อย่างชัดเจนในแอปพลิเคชันจะช่วยให้เข้าถึงฟังก์ชันและโมดูลทั้งหมดในไลบรารีได้
ในการสร้างแอปพลิเคชัน GUI ที่ใช้ matplotlib และฟังก์ชันของมัน เราต้องนำเข้าไลบรารีโดยใช้คำสั่ง จาก matplotlib.pyplot เป็น plt . อย่างไรก็ตาม เรายังใช้ Tkagg ในแบ็กเอนด์ที่ใช้อินเทอร์เฟซผู้ใช้ Tkinter แบบโต้ตอบ
ตัวอย่าง
ในตัวอย่างนี้ เราได้นำเข้า Tkagg และ matplotlib เพื่อแสดงภาพจุดข้อมูลที่กำหนดโดยพล็อตภายในวิดเจ็ตผ้าใบ
# Import required libraries
from tkinter import *
from tkinter import ttk
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# Create an instance of tkinter frame
win= Tk()
# Set the window size
win.geometry("700x350")
# Use TkAgg
matplotlib.use("TkAgg")
# Create a figure of specific size
figure = Figure(figsize=(3, 3), dpi=100)
# Define the points for plotting the figure
plot = figure.add_subplot(1, 1, 1)
plot.plot(0.5, 0.3, color="blue", marker="o", linestyle="")
# Define Data points for x and y axis
x = [0.2,0.5,0.8,1.0 ]
y = [ 1.0, 1.2, 1.3,1.4]
plot.plot(x, y, color="red", marker="x", linestyle="")
# Add a canvas widget to associate the figure with canvas
canvas = FigureCanvasTkAgg(figure, win)
canvas.get_tk_widget().grid(row=0, column=0)
win.mainloop() ผลลัพธ์
เมื่อเราเรียกใช้โค้ดข้างต้น พล็อตจะปรากฏขึ้นในหน้าต่างพร้อมจุดข้อมูลบางส่วนบนแกน X และ Y
