2014-01-17 156 views
1

我是相当新的python和一个真正的初学者tkinter和matplotlib。 我有以下代码基本上是我最终想要做的测试。嵌入动画matplotlib在tk

#!/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) 

当然这可能只是我只是不理解这个正确

回答

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() 
+0

感谢但这只是我遇到的问题。我无法让它从我生成的列表中获取数据。无论我尝试什么,都会抱怨。下面是一些错误的: – Buteman

+0

文件 “./anim3.py”,第29行,在 线= ax.plot(X,Y) 提高ValueError异常( “x和y必须具有相同的第一维”) ValueError:x和y必须具有相同的第一维 如果你看看我的原始代码,你会看到我读取一个文件,并用这些值填充一个列表,然后该图将这些值用作y坐标。我无法找到正确的方式来喂它在 – Buteman

+0

它工作正常,如果我不试图将其嵌入到根窗口或框架或其他任何事情。如果您粘贴代码并将其保存为python脚本并使用其他脚本生成初始数据文件,并将其保存在同一目录中,那么它将很有用。 – Buteman