如何在 Tkinter 中執行 Matplotlib?


Python Matplotlib 庫在許多應用程式中都有幫助,用於以圖表和圖形的形式直觀地呈現給定的資料和資訊。可以在 Tkinter 應用程式中執行 Matplotlib。通常,在應用程式中明確匯入任何 Python 庫都可以訪問該庫中的所有函式和模組。

要建立一個使用 Matplotlib 和其函式的 GUI 應用程式,我們必須使用以下命令匯入此庫 **from matplotlib.pyplot as 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 軸上某些資料點的圖表。

更新於: 07-6 月-2021

1 千+ 瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.