【问题标题】:Python matplotlib tkinter - button doesn't update graphPython matplotlib tkinter - 按钮不更新图形
【发布时间】:2020-02-27 13:39:00
【问题描述】:

我正在编写一个小程序,目的是在整个过程中定期更新 matplotlib 图。为此,我打算使用 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()   

【问题讨论】:

标签: python matplotlib tkinter tkinter-canvas


【解决方案1】:

在这种情况下,您需要“更新”画布。

将您的画布定义为:self.canvas = FigureCanvasTkAgg(fig_sig, master=root)

并“更新”它:

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

【讨论】:

  • 那么它是如何工作的 graph.clear()add_graph 内部被调用,因为这是在第一次调用 canvas.draw 之后发生的?
  • @RFairey 读取 Python 和 Tkinter lambda 函数 - stackoverflow.com/questions/11005401/…
  • 我先尝试过,但没有帮助(尽管我同意一旦屏幕上有几个情节,它就会变得很重要)。仅在update_graph 中调用canvas.draw() 即可解决问题,但取消注释原始graph.clear() 仍然有效,即使它在canvas.draw() 之后,并且不更改lambda。
猜你喜欢
  • 2022-11-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-23
  • 2022-08-13
  • 2020-10-03
  • 1970-01-01
  • 2017-12-19
  • 2016-01-20
相关资源
最近更新 更多