【问题标题】:Matplotlib animation in Tkinter TopLevel not workingTkinter TopLevel 中的 Matplotlib 动画不起作用
【发布时间】:2020-08-13 19:11:10
【问题描述】:

我找到了this thread,但我的情况有点不同,因为我希望我的情节存在于单独的窗口中,因此创建了以下类:

import tkinter as tk
import random

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib import pyplot, animation

class Graphs(tk.Toplevel):

    sensor_data = []
    steps = []

    def __init__(self, master): # master here is my root tk window
        super().__init__(master)
        self.title("Plot me some data")

        self.figure = pyplot.figure(dpi=150)
        self.sensor = figure.subplots(1, 1, 1)

        self.sensor.grid(True)
        self.line, = self.sensor.plot(self.steps, self.sensor_data)

        self.canvas = FigureCanvasTkAgg(figure, self)
        self.canvas.get_tk_widget().grid(column=0, row=0)

    def animate(self):
        ani = animation.FuncAnimation(self.figure, self.animation, fargs=(self,), blit=False, interval=1000)


    """
    This is a dumb logic to visualise if animation FuncAnimation is working
    """
    @staticmethod
    def animation(i, self):
        self.steps.append(i)
        self.sensor_data.append(self.steps[-1] * random.randint(-5, 5))
        self.line.set_data(self.steps, self.sensor_data[-1])

从主控制器我称之为:

    self.graphs = Graphs(self)
    self.graphs.animate()

所以,由于动画不工作,我迷路了。尝试在动画函数逻辑中调试代码设置断点,它永远不会停止让我认为动画从未开始的原因。任何提示我在这里错过或做错了什么?

【问题讨论】:

    标签: python matplotlib canvas tkinter


    【解决方案1】:

    最后,我发现了问题所在 - ani 变量必须是 self 的显式成员,所以行:

        self.ani = animation.FuncAnimation(self.figure, self.animation, fargs=(self,), blit=False, interval=1000)
    

    修复了在单独的类中定义并在 Tk TopLevel 中呈现时损坏的动画。

    【讨论】:

      猜你喜欢
      • 2015-03-03
      • 2015-04-16
      • 2021-01-18
      • 2018-06-19
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 2015-06-08
      • 2016-06-21
      相关资源
      最近更新 更多