# 【原】使用Tkinter绘制GUI并结合Matplotlib实现交互式绘图

   1: #!/usr/bin/env python
   2: #coding:utf-8
   3: """
   4:   Author:  Chaos --<Chaosimpler@gmail.com>
   5:   Purpose: 修改Matplotlib的后端，实现在Tkinter的GUI绘制图像
   6:   Created: 2014-10-15
   7: """
   8: import numpy as np
   9: from Tkinter import *
  10: import matplotlib
  11: from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
  12: from matplotlib.figure import Figure
  13:
  14: #----------------------------------------------------------------------
  15: def drawPic():
  16:     """
  17:     获取GUI界面设置的参数，利用该参数绘制图片
  18:     """
  19:
  20:     #获取GUI界面上的参数
  21:     try:sampleCount=int(inputEntry.get())
  22:     except:
  23:         sampleCount=50
  24:         print '请输入整数'
  25:         inputEntry.delete(0,END)
  26:         inputEntry.insert(0,'50')
  27:
  28:     #清空图像，以使得前后两次绘制的图像不会重叠
  29:     drawPic.f.clf()
  30:     drawPic.a=drawPic.f.add_subplot(111)
  31:
  32:     #在[0,100]范围内随机生成sampleCount个数据点
  33:     x=np.random.randint(0,100,size=sampleCount)
  34:     y=np.random.randint(0,100,size=sampleCount)
  35:     color=['b','r','y','g']
  36:
  37:     #绘制这些随机点的散点图，颜色随机选取
  38:     drawPic.a.scatter(x,y,s=3,color=color[np.random.randint(len(color))])
  39:     drawPic.a.set_title('Demo: Draw N Random Dot')
  40:     drawPic.canvas.show()
  41:
  42:
  43: if __name__ == '__main__':
  44:
  45:     matplotlib.use('TkAgg')
  46:     root=Tk()
  47:
  48:     #在Tk的GUI上放置一个画布，并用.grid()来调整布局
  49:     drawPic.f = Figure(figsize=(5,4), dpi=100)
  50:     drawPic.canvas = FigureCanvasTkAgg(drawPic.f, master=root)
  51:     drawPic.canvas.show()
  52:     drawPic.canvas.get_tk_widget().grid(row=0, columnspan=3)
  53:
  54:     #放置标签、文本框和按钮等部件，并设置文本框的默认值和按钮的事件函数
  55:     Label(root,text='请输入样本数量：').grid(row=1,column=0)
  56:     inputEntry=Entry(root)
  57:     inputEntry.grid(row=1,column=1)
  58:     inputEntry.insert(0,'50')
  59:     Button(root,text='画图',command=drawPic).grid(row=1,column=2,columnspan=3)
  60:
  61:     #启动事件循环
  62:     root.mainloop()
posted @ 2014-10-16 21:01  ChaoSimple  阅读(31998)  评论(5编辑  收藏  举报