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

yipeiwu_com7年前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程序设计有所帮助。

相关文章

pytorch forward两个参数实例

以channel Attention Block为例子 class CAB(nn.Module): def __init__(self, in_channels, out_c...

如何优雅地处理Django中的favicon.ico图标详解

前言 favicon.ico是网站的图标也是网站的头像,简单来说,就是让我们的网站更加好看。 本文主要给大家介绍了关于优雅处理Django中favicon.ico图标的相关内容,分享出来...

Python实现全角半角字符互转的方法

前言 相信对于每一个编程人员来说,在文本处理的时候,经常会遇到全角半角不一致的问题。于是需要程序能够快速的在两者之间互转。由于全角半角本身存在着映射关系,所以处理起来并不复杂。 具体规则...

Django Rest framework之权限的实现示例

Django Rest framework之权限的实现示例

一、权限实例 在阅读本文之前请先参考django rest framework 之 认证 中关于 django rest framework 的相关内容及实例 1、目录结构 为了更好的管...

python开发之anaconda以及win7下安装gensim的方法

一、推荐安装Anaconda 官方介绍:Anaconda is a completely free Python distribution (including for commerci...