本文實例講述了Python實現在tkinter中使用matplotlib繪制圖形的方法。分享給大家供大家參考,具體如下:
一. 代碼:
# coding=utf-8import sysimport Tkinter as Tkimport matplotlibfrom numpy import arange, sin, pifrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAggfrom matplotlib.backend_bases import key_press_handlerfrom matplotlib.figure import Figurematplotlib.use('TkAgg')root =Tk.Tk()root.title("武林站長站測試 - matplotlib in TK")#設置圖形尺寸與質量f =Figure(figsize=(5,4), dpi=100)a = f.add_subplot(111)t = arange(0.0,3,0.01)s = sin(2*pi*t)#繪制圖形a.plot(t, s)#把繪制的圖形顯示到tkinter窗口上canvas =FigureCanvasTkAgg(f, master=root)canvas.show()canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)#把matplotlib繪制圖形的導航工具欄顯示到tkinter窗口上toolbar =NavigationToolbar2TkAgg(canvas, root)toolbar.update()canvas._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)#定義并綁定鍵盤事件處理函數def on_key_event(event): print('you pressed %s'% event.key) key_press_handler(event, canvas, toolbar) canvas.mpl_connect('key_press_event', on_key_event)#按鈕單擊事件處理函數def _quit(): #結束事件主循環,并銷毀應用程序窗口 root.quit() root.destroy()button =Tk.Button(master=root, text='Quit', command=_quit)button.pack(side=Tk.BOTTOM)Tk.mainloop()二. 運行結果:

更多關于Python相關內容可查看本站專題:《Python數學運算技巧總結》、《Python正則表達式用法總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》及《Python入門與進階經典教程》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答