Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีรัน Matplotlib ใน Tkinter แสดงกราฟบน GUI

ภาพรวม

หนึ่งในกรณีการใช้งานยอดนิยมของ Python คือ Machine Learning และ Data Science สำหรับการแสดงผลและพลอตข้อมูล ใช้ไลบรารี Matplotlib เพื่อพลอตกราฟในแอปพลิเคชัน Tkinter ต้องนำเข้าไลบรารีโดยใช้ from matplotlib import pyplot as plt กราฟสามารถวาดได้โดยกำหนดค่า Range หรือนำเข้าชุดข้อมูล

ตัวอย่างโค้ด

# นำเข้าไลบรารีที่จำเป็น
from tkinter import *
from tkinter import ttk
import numpy as np
import matplotlib.pyplot as plt

# สร้าง instance ของ Tkinter frame
win = Tk()
win.geometry("700x250")

def graph():
    car_prices = np.random.normal(50000, 4000, 2000)
    plt.figure(figsize=(7, 3))
    plt.hist(car_prices, 25)
    plt.show()

# สร้างปุ่มเพื่อพลอตกราฟ
button = ttk.Button(win, text="Graph", command=graph)
button.pack()

win.mainloop()

ผลลัพธ์

การรันโค้ดจะแสดงหน้าต่างที่มีปุ่ม "Graph"

เมื่อคลิกปุ่ม "Graph" จะแสดงกราฟ Histogram บนหน้าต่างแยกของ Matplotlib