用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()
輸出
如果我們執行上述程式碼,它將顯示一個視窗,其中包含一個按鈕“顯示圖形”。
當我們單擊按鈕時,它將在螢幕上顯示圖形。
廣告