2

我对 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)

当然可能只是我没有正确理解这一点

4

1 回答 1

1

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

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()
于 2014-01-17T12:27:57.033 回答