将 matplotlib 动画嵌入到 tkinter 窗口中
当前,可视化已经成为数据分析中不可或缺的部分。对于数据分析人员来说,有时候会希望在特定场景下,将 matplotlib 的动画图形显示在 tkinter 窗口中。本文将介绍如何将 matplotlib 动画嵌入到 tkinter 窗口中。
前置条件
在开始之前,需要先安装以下依赖:
- tkinter
- matplotlib
安装 tkinter:
sudo apt-get install python3-tk
安装 matplotlib:
pip install matplotlib
步骤
步骤一:创建 tkinter 窗口
首先,需要创建一个 tkinter 窗口,用于显示 matplotlib 动画:
import tkinter as tk
class MyApp(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("800x600")
self.canvas = tk.Canvas(self, width=800, height=600)
self.canvas.pack()
if __name__ == "__main__":
app = MyApp()
app.mainloop()
步骤二:创建 matplotlib 动画图形
接下来,需要创建 matplotlib 动画图形,这里以随机数为例,进行一个简单的示例:
import matplotlib.pyplot as plt
import numpy as np
class MyAnimation:
def __init__(self, canvas):
self.fig = plt.figure()
self.ax = self.fig.add_subplot(111)
self.canvas = canvas
def init(self):
pass
def animate(self, i):
self.ax.clear()
x = np.random.normal(0,1,1000)
y = np.random.normal(0,1,1000)
self.ax.scatter(x, y)
self.canvas.draw()
if __name__ == "__main__":
app = MyApp()
my_animation = MyAnimation(app.canvas)
app.mainloop()
步骤三:将 matplotlib 动画嵌入到 tkinter 窗口中
最后一步,就是将 Step2 中创建的 matplotlib 动画图形嵌入到 tkinter 窗口中。
import tkinter as tk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
class MyApp(tk.Tk):
def __init__(self):
super().__init__()
self.geometry("800x600")
self.canvas = tk.Canvas(self, width=800, height=600)
self.canvas.pack()
self.anim = self.create_animation()
self.anim_running = True
self.toolbar = self.create_toolbar()
self.bind('<Configure>', self.resize)
self.bind('<Escape>', lambda e: self.quit())
self.protocol("WM_DELETE_WINDOW", self.quit)
def create_animation(self):
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_xlim(-4, 4)
ax.set_ylim(-4, 4)
scat = ax.scatter([], [])
def init():
return (scat, )
def animate(i):
x = np.random.normal(0,1,1000)
y = np.random.normal(0,1,1000)
scat.set_offsets(np.c_[x, y])
return (scat, )
anim = FuncAnimation(fig, animate, init_func=init, blit=True)
return anim
def create_toolbar(self):
toolbar = tk.Frame(self, relief=tk.RAISED, borderwidth=1)
toolbar.pack(side=tk.BOTTOM, fill=tk.X)
button1 = tk.Button(toolbar, text="Start", command=self.start_pause)
button1.pack(side=tk.LEFT, padx=2, pady=2)
button2 = tk.Button(toolbar, text="Stop", command=self.stop)
button2.pack(side=tk.LEFT, padx=2, pady=2)
return toolbar
def start_pause(self):
if self.anim_running:
self.anim.event_source.stop()
self.anim_running = False
else:
self.anim.event_source.start()
self.anim_running = True
def stop(self):
self.anim._stop()
def resize(self, event):
self.anim._stop()
self.anim = self.create_animation()
self.anim_running = True
self.anim.event_source.start()
self.anim.canvas.draw()
def quit(self):
plt.close('all')
self.destroy()
if __name__ == "__main__":
app = MyApp()
app.mainloop()
在 Step 3 中,我们使用了 FigureCanvasTkAgg
类和 FuncAnimation
类来处理 matplotlib 动画图形。
结论
本文介绍了如何将 matplotlib 动画嵌入到 tkinter 窗口中。首先,需要创建一个 tkinter 窗口,然后创建 matplotlib 动画图形,并最终将 matplotlib 动画嵌入到 tkinter 窗口中。借助于 tkinter 和 matplotlib,我们可以更好地对数据进行可视化和分析。