怎么通过交互模式把matplotlib动图嵌入tkinter中,不用FuncAnimation函数
时间: 2024-03-05 20:54:25 浏览: 20
可以使用`canvas`和`after`方法来将matplotlib动图嵌入Tkinter中,示例代码如下:
```python
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
class AnimatedPlot:
def __init__(self, master):
self.master = master
self.fig = Figure(figsize=(5, 4), dpi=100)
self.ax = self.fig.add_subplot(111)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.master)
self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
self.line, = self.ax.plot([], [], lw=2)
self.xdata, self.ydata = [], []
self.anim_running = False
def init(self):
self.line.set_data([], [])
return self.line,
def update(self, i):
t = 0.1 * i
x = np.sin(2 * np.pi * t)
y = np.cos(2 * np.pi * t)
self.xdata.append(x)
self.ydata.append(y)
self.line.set_data(self.xdata, self.ydata)
self.ax.relim()
self.ax.autoscale_view()
return self.line,
def start_animation(self):
self.anim_running = True
self.animate()
def stop_animation(self):
self.anim_running = False
def animate(self):
if self.anim_running:
self.update(len(self.xdata))
self.canvas.draw()
self.master.after(50, self.animate)
if __name__ == "__main__":
root = tk.Tk()
root.geometry("500x400")
plot = AnimatedPlot(root)
start_button = tk.Button(root, text="Start", command=plot.start_animation)
start_button.pack(side=tk.LEFT, padx=10, pady=10)
stop_button = tk.Button(root, text="Stop", command=plot.stop_animation)
stop_button.pack(side=tk.LEFT, padx=10, pady=10)
root.mainloop()
```
在这个示例中,我们定义了一个`AnimatedPlot`类,它包含了一个`Figure`对象和一个`FigureCanvasTkAgg`对象,用于将matplotlib的绘图结果显示在Tkinter窗口中。`AnimatedPlot`类中定义了`init()`和`update()`方法,分别用于初始化动图和更新动图。`start_animation()`和`stop_animation()`方法分别用于启动和停止动画。在`animate()`方法中使用`after`方法来定时更新动画。
在这个示例中,我们使用了`sin`和`cos`函数生成了一个简单的动画,你可以根据自己的需求来修改这个动画。