如何在 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 轴上某些数据点的图表。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP