问题
I am fairly new to python and a real beginner to tkinter and matplotlib. I have the following code which essentially is a testbed for what I eventually want to do.
#!/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)
How can I embed this in tkinter. I have searched for hours and have come across many suggestions but it seems none of them apply to dynamic plots. If anyone wants to see the data this program is using I created it with the following code.
#!/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)
Of course it may just be that I am just not understanding this correctly
回答1:
Here is an example, I added a button that will start animation:
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()
来源:https://stackoverflow.com/questions/21179971/embedding-an-animated-matplotlib-in-tk