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简单检测文本类型的2种方法【基于文件头及cchardet库】

本文实例讲述了Python简单检测文本类型的方法。分享给大家供大家参考,具体如下: 1、根据文件头。 #是否为带BOM头的UTF8文件 def IsUtf8BomFile(pathf...

python入门:这篇文章带你直接学会python

python入门:这篇文章带你直接学会python

初试牛刀 假设你希望学习Python这门语言,却苦于找不到一个简短而全面的入门教程。那么本教程将花费十分钟的时间带你走入Python的大门。本文的内容介于教程(Toturial)和速查手...

Unicode和Python的中文处理

在Python语言中,Uincode字符串处理一直是一个容易让人迷惑的问题。许多Python爱好者经常因为搞不清Unicode、UTF-8还有其它许许多多的编码之间的区别而大伤脑筋。笔者...

pandas 选择某几列的方法

如下所示: col_n = ['名称','收盘价','日期'] a = pd.DataFrame(df,columns = col_n) 以上这篇pandas 选择某几列的方法就...

python+selenium实现163邮箱自动登陆的方法

python+selenium实现163邮箱自动登陆的方法

本文介绍了 让我们先来预览一下代码运行效果吧: 首先分析163邮箱登陆页面的网页结构(按F12或单击鼠标右键选择审查元素) 1、定位到登陆框(注意登录框是一个iframe,如果不定位...