【问题标题】:Embedding an animated matplotlib in tk在 tk 中嵌入动画 matplotlib
【发布时间】:2014-01-17 07:14:52
【问题描述】:

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

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

【问题讨论】:

    标签: python matplotlib tkinter python-embedding


    【解决方案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()
    

    【讨论】:

    • 谢谢,但这只是我遇到的问题。我无法让它从我生成的列表中获取数据。无论我尝试什么,它都会抱怨。以下是一些错误:
    • 文件 "./anim3.py",第 29 行,在 行中,= ax.plot(x, y) raise ValueError("x and y must have same first dimension") ValueError :x 和 y 必须具有相同的第一个维度如果您查看我的原始代码,您会看到我读取了一个文件并用这些值填充了一个列表,然后绘图使用这些值作为 y 坐标。我找不到正确的喂食方式
    • 如果我不尝试将它嵌入根窗口或框架或其他任何东西,它工作正常。如果将代码粘贴并保存为python脚本并使用其他脚本生成初始数据文件,将其保存在同一目录中,效果会很好。
    猜你喜欢
    • 2017-05-05
    • 2016-12-05
    • 2020-07-21
    • 1970-01-01
    • 2014-02-07
    • 2016-04-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    相关资源
    最近更新 更多