Python matplotlib tkinter-按钮不';t更新图

Python matplotlib tkinter-按钮不';t更新图,python,matplotlib,tkinter,tkinter-canvas,Python,Matplotlib,Tkinter,Tkinter Canvas,我正在编写一个小程序,打算在整个过程中定期更新matplotlib图。为此,我打算使用clear()并重新绘制图形。当从创建图形的方法中调用clear函数时,clear函数确实有效,但当从按钮调用时,即使图形作为参数给定,clear函数也不起作用 下面是最基本形式的可运行代码来说明问题。 在这种情况下,单击“更新”按钮不起任何作用。我如何修复该按钮以清除图表 import matplotlib.pyplot as plt from matplotlib.backends.backend_tka

我正在编写一个小程序,打算在整个过程中定期更新matplotlib图。为此,我打算使用clear()并重新绘制图形。当从创建图形的方法中调用clear函数时,clear函数确实有效,但当从按钮调用时,即使图形作为参数给定,clear函数也不起作用

下面是最基本形式的可运行代码来说明问题。 在这种情况下,单击“更新”按钮不起任何作用。我如何修复该按钮以清除图表

import matplotlib.pyplot as plt 
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import tkinter as tk
import numpy as np

class MainWindow(tk.Frame):
    def __init__(self, master = None):
        tk.Frame.__init__(self, master)
        self.add_graph()

    def add_graph(self):         
        fig_sig = plt.figure(figsize=(4,2))
        graph = fig_sig.add_subplot(111)
        y_values = [0,1,2,3,4,5]   
        x_values = [1,2,3,4,5,6]
        graph.plot(x_values, y_values)
        canvas = FigureCanvasTkAgg(fig_sig, master=root)
        canvas_widget=canvas.get_tk_widget()   
        canvas_widget.grid(row = 1, column = 0, columnspan = 3)
        canvas.draw()
        self.add_widgets(root, graph)
        #graph.clear()  # Calling graph.clear() here does clear the graph

    def add_widgets(self, parent, graph):
        update_btn = tk.Button(parent, text = "Update", command = lambda: self.update_graph(graph))
        update_btn.grid(row = 8, column = 3)

    def update_graph(self, graph):
        graph.clear()   # calling graph.clear() here does nothing

root = tk.Tk()
oberflaeche = MainWindow(master = root)
oberflaeche.mainloop()   
在这种情况下,您需要“更新”画布

将画布定义为:
self.canvas=FigureCanvasTkAgg(fig\u sig,master=root)

和“更新”它:


阅读它是如何工作的
graph.clear()
add\u graph
中被调用,因为这是在第一次调用
canvas.draw
?@RFairey Read Python和Tkinter lambda函数之后发生的-我先尝试了,但没有帮助(尽管我同意一旦屏幕上有几个绘图,它就会变得很重要)。仅在
update\u graph
中调用
canvas.draw()
解决了答案中的问题,但取消对原始
graph.clear()的注释仍然有效,即使它位于canvas.draw()之后,并且不更改lambda。
def update_graph(self, graph):
    graph.clear()   # calling graph.clear() here does nothing
    self.canvas.draw()