Python实现在tkinter中使用matplotlib绘制图形的方法示例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现在tkinter中使用matplotlib绘制图形的方法。分享给大家供大家参考,具体如下:

一. 代码:

# 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("【听图阁-专注于Python设计】测试 - 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程序设计有所帮助。

相关文章

图解Python变量与赋值

图解Python变量与赋值

Python是一门独特的语言,与C语言有很大区别,初学Python很多萌新表示对变量与赋值不理解,学过C的都知道,给变量赋值时,需要先指定数据类型,同时会开辟一块内存区域,用于存储值,例...

Python线程池模块ThreadPoolExecutor用法分析

本文实例讲述了Python线程池模块ThreadPoolExecutor用法。分享给大家供大家参考,具体如下: python3内置的有Threadingpool和ThreadPoolEx...

python 3利用Dlib 19.7实现摄像头人脸检测特征点标定

python 3利用Dlib 19.7实现摄像头人脸检测特征点标定

Python 3 利用 Dlib 19.7 实现摄像头人脸检测特征点标定 0.引言 利用python开发,借助Dlib库捕获摄像头中的人脸,进行实时特征点标定; 图1 工程效果示例(...

SublimeText 2编译python出错的解决方法(The system cannot find the file specified)

[Error 2] The system cannot find the file specified 解决方法:1.环境变量path添加:C:\Python32\Tools\Scrip...

实例讲解python中的序列化知识点

在程序运行的过程中,所有的变量都是在内存中,比如,定义一个dict: d = dict(name='Bob', age=20, score=88) 可以随时修改变量,比如把name...