Python圖形之-tkinter與matplotlib結合案例


 

使用matplotlib繪制圖像,並顯示到thinter已有的畫布中,如何進行兩個包的連接,具體案例如下:

 1 import matplotlib
 2 matplotlib.use('TkAgg')
 3 from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
 4 from matplotlib.figure import Figure
 5 from tkinter import *
 6 root = Tk()
 7 root.title("tkinter and matplotlib")
 8 f = Figure(figsize=(2.52, 2.56), dpi=100)#figsize定義圖像大小,dpi定義像素
 9 f_plot = f.add_subplot(111)#定義畫布中的位置
10 def other_picture_alg(): #數據相關的算法應該與plot分離開
11     x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
12     y = [3, 6, 9, 12, 15, 18, 15, 12, 15, 18]
13     return x, y
14 def draw_picture():
15     f_plot.clear()
16     x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #關於數據的部分可以提取出來
17     y = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]
18     f_plot.plot(x, y)
19     canvs.draw()
20 def draw_picture2():
21     f_plot.clear()
22     x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] #關於數據的部分可以提取出來
23     y = [2, 4, 6, 8, 10, 8, 6, 4, 2, 0]
24     f_plot.plot(x, y)
25     canvs.draw()
26 def draw_picture3():
27     f_plot.clear()
28     x, y = other_picture_alg() # 使用由算法生成的數據,可以避免重復的運算過程
29     f_plot.plot(x, y)
30     canvs.draw()
31 canvs = FigureCanvasTkAgg(f, root)#f是定義的圖像,root是tkinter中畫布的定義位置
32 canvs.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1)
33 Button(root, text='pic', command=draw_picture).pack()
34 Button(root, text='pic2', command=draw_picture2).pack()
35 Button(root, text='pic3', command=draw_picture3).pack()
36 root.mainloop()

運行結果如圖:

如圖所示,先定義畫布大小以及圖像位置,pic顯示是直線,坐標點手動定義;pic2顯示是折線,坐標點手動定義;pic3顯示是折線,坐標點手動定義;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM