在tk中嵌入动画matplotlib

时间:2014-01-17 07:14:53

标签: python matplotlib tkinter python-embedding

我是python的新手,是tkinter和matplotlib的真正初学者。 我有以下代码,它基本上是我最终想要做的测试平台。

#!/usr/bin/env python 
import  numpy as np
from  matplotlib import  pyplot as plt
import time

top = 100
plt.ion () # set plot to animated
xdata = []
c = 0
for a in range(0,top):
 xdata.append(a)
 c+=1
ydata =  [ 0 ] *  top * 10
ax1 = plt.axes ()  
c = 0
myfile = open("rdata.txt", "r")
for myline in myfile:
q = myline
ydata[c] = q 
c+=1
c = 0
# Make plot
line, =  plt.plot (ydata[0:60])

myfile = open("rdata.txt", "r")

for p in range(0, top * 10):
for myline in myfile:
      q = int(myline)
      ydata.append (q)
      del  ydata [ 0 ]
      line.set_xdata (np.arange ( len (ydata)))
      line.set_ydata (ydata)   # update the data
      time.sleep(0.01)
      plt.draw () # update the plot 

#   c +=1


file.close(myfile)

如何将其嵌入tkinter中。 我搜索了几个小时并且遇到了很多建议,但似乎没有一个适用于动态图。 如果有人想查看该程序正在使用的数据,我使用以下代码创建它。

#!/usr/bin/env python
import random

myfile = open("rdata.txt", "w")
myfile.write("100\n")
myfile.write("0\n")
for x in range(2,100):
 q = random.randint(10,90)
 myfile.write(str(q))
 myfile.write("\n")

file.close(myfile)

当然可能只是因为我没有正确理解

1 个答案:

答案 0 :(得分:0)

这是一个例子,我添加了一个启动动画的按钮:

import numpy as np
import matplotlib

matplotlib.use("TKAgg")
import pylab as pl
fig, ax = pl.subplots()
p = 0
x = np.linspace(0, 10, 200)
y = np.sin(x+p)
line, = ax.plot(x, y)
canvas = fig.canvas.get_tk_widget()

from Tkinter import Button

def anim():
    global p
    p += 0.04
    y = np.sin(x+p)
    line.set_data(x, y)
    fig.canvas.draw()
    canvas.after(50, anim)

def go():
    anim()

b = Button(canvas.master, text="go", command=go)
b.pack()
pl.show()