Embed a pyplot in a tkinter window and update it

后端 未结 1 1426
心在旅途
心在旅途 2020-12-14 13:27

I am trying to write a program that has a pyplot (as in matplotlib.pyplot) within a Tkinter GUI which can be updated. Basically what I want is a program with a Tkinter inter

相关标签:
1条回答
  • 2020-12-14 14:09

    I figured it out, I need to call the draw() method on the figure's canvas attribute in order to get it to redraw, the corrected code is below. Also anyone who is encountering this or similar problems should probably look at matplotlib.animate if they need to be dynamically updating their 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()
    
    0 讨论(0)
提交回复
热议问题