gpt4 book ai didi

Python matplotlib tkinter - 按钮不更新图形

转载 作者:行者123 更新时间:2023-12-04 10:30:42 28 4
gpt4 key购买 nike

我正在编写一个小程序,目的是在整个过程中定期更新 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()

最佳答案

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

将您的 Canvas 定义为:self.canvas = FigureCanvasTkAgg(fig_sig, master=root)
并“更新”它:

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

关于Python matplotlib tkinter - 按钮不更新图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60434549/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com