简体   繁体   中英

Update plot matplotlib tkinter

I have the following piece of code:

import tkinter as tk
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg)
from matplotlib.figure import Figure

root = tk.Tk()

figure = Figure()
figure_canvas = FigureCanvasTkAgg(figure,master=root) 

axes = figure.add_subplot(1,1,1)
axes.plot([1,2,3],[1,2,3])

figure_to_pack_d1 = figure_canvas.get_tk_widget()
figure_to_pack_d1.pack(fill=tk.BOTH)

def plot_axes():
    axes.clear()
    axes.plot([1,2,3],[3,2,1])
tk.Button(root,command=plot_axes,text="Update plot").pack()

root.mainloop()

It's supposed to generate a simple GUI with a matplotlib plot and a button (done correctly). When you press the button, the plot should change. When the button gets pressed, seems that nothing is happening, but if you force to update the window (changing it's size) it gets updated correctly. Is there any way to update the plot immediatly after the button is pressed? I've tried some methods like root.update() , axes.update({}) , figure.canvas.flush_events() ... But none of them worked.

Thank you so much!

I was finnaly able to find my own answer. The actual way to update the plot is with de command:

figure_canvas.draw()

So, the script looks like:

import tkinter as tk
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg)
from matplotlib.figure import Figure

root = tk.Tk()

figure = Figure()
figure_canvas = FigureCanvasTkAgg(figure,master=root) 

axes = figure.add_subplot(1,1,1)
axes.plot([1,2,3],[1,2,3])

figure_to_pack_d1 = figure_canvas.get_tk_widget()
figure_to_pack_d1.pack(fill=tk.BOTH)

def plot_axes():
    axes.clear()
    axes.plot([1,2,3],[3,2,1])
    figure_canvas.draw()
tk.Button(root,command=plot_axes,text="Update plot").pack()

root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM