Embedding a matplotlib animation into a tkinter frame

MatplotlibPythonData Visualization

To embed a matplotlib animation into a tkinter frame, we can take the following steps


  • Set the figure size and adjust the padding between and around the subplots.

  • Create a Toplevel widget of Tk which represents mostly the main window of an application

  • Set the title of this widget.

  • Add an axes to the current figure and make it the current axes.

  • Create a new figure or activate an existing figure.

  • Add an 'ax' to the figure as part of a subplot arrangement.

  • Make a dummy line plot with linewidth=2.

  • Create the canvas the figure renders into.

  • Create the figure canvas on which to operate.

  • Create a keypress event to quit the tkinter winter.

  • Create an animation by repeatedly calling a function *animate*.

  • To display the figure, use Show() method.


import tkinter
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)
from matplotlib.backend_bases import key_press_handler
from matplotlib import pyplot as plt, animation
import numpy as np

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

root = tkinter.Tk()
root.wm_title("Embedding in Tk")

plt.axes(xlim=(0, 2), ylim=(-2, 2))
fig = plt.Figure(dpi=100)
ax = fig.add_subplot(xlim=(0, 2), ylim=(-1, 1))
line, = ax.plot([], [], lw=2)

canvas = FigureCanvasTkAgg(fig, master=root)

toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)

    "key_press_event", lambda event: print(f"you pressed {event.key}"))
canvas.mpl_connect("key_press_event", key_press_handler)

button = tkinter.Button(master=root, text="Quit", command=root.quit)

toolbar.pack(side=tkinter.BOTTOM, fill=tkinter.X)
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)

def init():
    line.set_data([], [])
    return line,

def animate(i):
    x = np.linspace(0, 2, 1000)
    y = np.sin(2 * np.pi * (x - 0.01 * i))
    line.set_data(x, y)
    return line,

anim = animation.FuncAnimation(fig, animate, init_func=init,frames=200, interval=20, blit=True)



It will produce the following output −

Updated on 09-Oct-2021 09:15:07