本文实例讲述了Python实现在tkinter中使用matplotlib绘制图形的方法。分享给大家供大家参考,具体如下:
一. 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
# coding=utf-8
import sys
import Tkinter as Tk
import matplotlib
from numpy import arange, sin, pi
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg,NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
matplotlib.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程序设计有所帮助。
原文链接:http://blog.csdn.net/chengqiuming/article/details/78601413