用Python在 Tkinter 主窗口中放置图表


很多时候,我们需要在基于 Tkinter GUI 的应用程序中处理图表。为了支持可用数据点的图表,Python 提供了一个 Matplotlib 包,可以轻松导入到应用程序中。为了给给定的数据点添加图表,我们必须安装其他几个包,例如 NumPy 和 Matplotlib。NumPy 是一个 Python 库,有助于处理数据中的科学计算。

示例

在此示例中,我们将创建从 (100000) 开始的汽车价格数据点,单位范围为 1000 到 5000。

#Import the required Libraries
from tkinter import *
import numpy as np
import matplotlib.pyplot as plt

#Create an instance of Tkinter frame
win= Tk()

#Set the geometry of tkinter frame
win.geometry("750x250")

def graph():
   car_prices=np.random.normal(100000, 5000, 1000)
   plt.hist(car_prices, 20)
   plt.show()

#Create a button to show the plot
Button(win, text= "Show Graph", command= graph).pack(pady=20)
win.mainloop()

输出

如果我们运行上述代码,它将显示一个窗口,其中包含一个按钮“显示图形”。

当我们单击按钮时,它将在屏幕上显示图形。

更新于: 2021 年 03 月 05 日

2K+ 浏览

开启你的职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.