【问题标题】:Embed a pyplot in a tkinter window and update it在 tkinter 窗口中嵌入 pyplot 并更新它
【发布时间】:2014-10-19 08:56:27
【问题描述】:

我正在尝试编写一个在 Tkinter GUI 中具有可更新的 pyplot(如 matplotlib.pyplot)的程序。基本上我想要的是一个带有 Tkinter 界面的程序在 pyplot 上显示一些数据,然后当程序获得一些新数据时,我想更新 pyplot 以包含新数据。

这是一个最小的例子:

import numpy as np
import Tkinter as tk

import matplotlib
matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt

root = tk.Tk()

fig = plt.figure(1)
t = np.arange(0.0,3.0,0.01)
s = np.sin(np.pi*t)
plt.plot(t,s)

canvas = FigureCanvasTkAgg(fig, master=root)
plot_widget = canvas.get_tk_widget()

def update():
    s = np.cos(np.pi*t)
    plt.plot(t,s)
    plt.draw()

plot_widget.grid(row=0, column=0)
tk.Button(root,text="Update",command=update).grid(row=1, column=0)
root.mainloop()

我期望发生的是,弹出一个窗口,其中包含一个正弦波和一个按钮的图。当我按下按钮时,绘图上应该会出现一个余弦波。

当我运行程序时,实际发生的情况是会弹出一个窗口,其中包含一个正弦波和一个按钮。但是,当我按下按钮时,什么也没有发生。剧情似乎没有更新。

我可能犯了一些新手错误,但我在网上找不到任何做这种事情的例子。这里出了什么问题,我该如何得到我想要的?

任何帮助将不胜感激!

【问题讨论】:

    标签: python-2.7 matplotlib


    【解决方案1】:

    我想通了,我需要在图形的canvas属性上调用draw()方法才能让它重绘,更正的代码如下。此外,遇到此或类似问题的任何人都应该查看 matplotlib.animate 如果他们需要动态更新他们的 pyplot

    import numpy as np
    import Tkinter as tk
    
    import matplotlib
    matplotlib.use('TkAgg')
    
    from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
    import matplotlib.pyplot as plt
    
    root = tk.Tk()
    
    fig = plt.figure(1)
    plt.ion()
    t = np.arange(0.0,3.0,0.01)
    s = np.sin(np.pi*t)
    plt.plot(t,s)
    
    canvas = FigureCanvasTkAgg(fig, master=root)
    plot_widget = canvas.get_tk_widget()
    
    def update():
        s = np.cos(np.pi*t)
        plt.plot(t,s)
        #d[0].set_ydata(s)
        fig.canvas.draw()
    
    plot_widget.grid(row=0, column=0)
    tk.Button(root,text="Update",command=update).grid(row=1, column=0)
    root.mainloop()
    

    【讨论】:

      猜你喜欢
      • 2023-04-01
      • 1970-01-01
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      相关资源
      最近更新 更多