简体   繁体   English

更新 plot matplotlib tkinter

[英]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).它应该使用 matplotlib plot 和一个按钮(正确完成)生成一个简单的 GUI。 When you press the button, the plot should change.当您按下按钮时,plot 应该会发生变化。 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.当按钮被按下时,似乎什么都没有发生,但如果你强制更新 window(改变它的大小)它会正确更新。 Is there any way to update the plot immediatly after the button is pressed?有什么方法可以在按下按钮后立即更新 plot? I've tried some methods like root.update() , axes.update({}) , figure.canvas.flush_events() ... But none of them worked.我尝试了一些方法,如root.update()axes.update({})figure.canvas.flush_events() ...但它们都没有奏效。

Thank you so much!太感谢了!

I was finnaly able to find my own answer.我终于找到了自己的答案。 The actual way to update the plot is with de command:更新plot 的实际方法是使用 de 命令:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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