Embedding a matplotlib animation into a tkinter frame

To embed a matplotlib animation into a tkinter frame, we need to combine matplotlib's animation capabilities with tkinter's GUI framework using the TkAgg backend.

Key Components

The integration requires several key components ?

  • FigureCanvasTkAgg − Creates the canvas where matplotlib renders the figure

  • NavigationToolbar2Tk − Provides zoom, pan, and navigation controls

  • FuncAnimation − Handles the animation loop and frame updates

  • Animation functionsinit() and animate() functions to control the animation

Complete Example

Here's a complete example that creates an animated sine wave in a tkinter window ?

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

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

# Create tkinter root window
root = tkinter.Tk()
root.wm_title("Embedding Matplotlib Animation in Tkinter")

# Create matplotlib figure and axes
fig = plt.Figure(dpi=100)
ax = fig.add_subplot(xlim=(0, 2), ylim=(-1, 1))
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_title('Animated Sine Wave')
line, = ax.plot([], [], lw=2, color='blue')

# Create canvas and embed in tkinter
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()

# Add navigation toolbar
toolbar = NavigationToolbar2Tk(canvas, root, pack_toolbar=False)
toolbar.update()

# Connect key press events
canvas.mpl_connect(
    "key_press_event", lambda event: print(f"You pressed {event.key}"))
canvas.mpl_connect("key_press_event", key_press_handler)

# Add quit button
button = tkinter.Button(master=root, text="Quit", command=root.quit)
button.pack(side=tkinter.BOTTOM)

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

# Animation functions
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,

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

# Start tkinter main loop
tkinter.mainloop()

How It Works

The animation works through these steps ?

  1. Figure Creation − A matplotlib Figure is created with specified DPI and size

  2. Canvas Integration − FigureCanvasTkAgg embeds the figure into the tkinter window

  3. Animation Loop − FuncAnimation repeatedly calls the animate() function

  4. Frame Updates − Each frame updates the line data to create motion

Key Parameters

Parameter Description Purpose
frames 200 Number of animation frames
interval 20 ms Delay between frames
blit True Optimize rendering performance

Output

The code creates a tkinter window with an animated sine wave. The wave continuously moves from right to left, and users can interact with the plot using the navigation toolbar.

Tkinter Window with Matplotlib Animation Animated Sine Wave Navigation Toolbar

Conclusion

Embedding matplotlib animations in tkinter requires the FigureCanvasTkAgg backend and FuncAnimation class. The key is creating proper init() and animate() functions that update the plot data each frame.

Updated on: 2026-03-26T15:02:13+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements