Matplotlib is a powerful Python library that is used for creating a variety of plots and graphs. Tkinter is a popular GUI toolkit for creating desktop applications in Python. In this tutorial, we will learn how to embed a Matplotlib graph into a Tkinter application.
Step 1: Install Matplotlib and Tkinter
Before we begin, make sure that you have Matplotlib and Tkinter installed on your system. You can install Matplotlib using pip by running the following command in your terminal:
pip install matplotlib
Tkinter is included with Python by default, so you do not need to install it separately.
Step 2: Create a basic Tkinter application
To get started, let’s create a basic Tkinter application with a blank canvas where we will embed our Matplotlib graph. Open a new Python file and add the following code:
import tkinter as tk
root = tk.Tk()
root.title("Embedding Matplotlib in Tkinter")
canvas = tk.Canvas(root, width=800, height=600)
canvas.pack()
root.mainloop()
Save the file as app.py
and run it. You should see a blank window with the title "Embedding Matplotlib in Tkinter".
Step 3: Create a Matplotlib graph
Next, let’s create a Matplotlib graph that we will embed into our Tkinter application. Add the following code to your app.py
file:
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
root = tk.Tk()
root.title("Embedding Matplotlib in Tkinter")
fig = Figure(figsize=(6, 4), dpi=100)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
Save the file and run it. You should see a basic Matplotlib graph displayed in the Tkinter window.
Step 4: Customize the Matplotlib graph
You can customize the Matplotlib graph by adding titles, labels, legends, and other elements. Here’s an example:
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
root = tk.Tk()
root.title("Embedding Matplotlib in Tkinter")
fig = Figure(figsize=(6, 4), dpi=100)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
ax.set_title('Sample Plot')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.legend(['Line 1'], loc='upper left')
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
root.mainloop()
Save the file and run it to see the updated Matplotlib graph with titles, labels, and a legend.
Step 5: Add interactive elements to the Tkinter application
You can add interactive elements to your Tkinter application that will update the Matplotlib graph dynamically. Here’s an example where we add a button that changes the data plotted on the graph when clicked:
import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
def update_data():
ax.clear()
ax.plot([1, 2, 3, 4, 5], [5, 4, 3, 2, 1])
ax.set_title('Updated Plot')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.legend(['Line 2'], loc='upper left')
canvas.draw()
root = tk.Tk()
root.title("Embedding Matplotlib in Tkinter")
fig = Figure(figsize=(6, 4), dpi=100)
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4, 5], [1, 2, 3, 4, 5])
ax.set_title('Sample Plot')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.legend(['Line 1'], loc='upper left')
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack()
update_button = tk.Button(root, text="Update Data", command=update_data)
update_button.pack()
root.mainloop()
Save the file and run it to see the Matplotlib graph with a button that updates the data when clicked.
Congratulations! You have successfully embedded a Matplotlib graph into a Tkinter application. Feel free to explore more customization options and interactive elements to create powerful data visualization tools in Python.
It's reassuring to know that I'm not the only one who wants to embed Matplotlib into Tkinter! 🥲
Thank you
👍👍👍
Quite useful, thank you for sharing such knowledge
very nice, thanks a lot dude! greetings from Spain 🙂
Thanks man! That really helped me a lot.
exactly what I need!
Perfect brother!!
How to create multiple graph on specific window by clicking a button of Tkinter?
great job buddy, Thank you for sharing
Many many thanks for such a short and concise video. much appreciated
Very helpful, thanks
Thanks. very helpful
Where is the data of the random points stored? The old random points were remembered and displayed when "Plot Graph" is clicked so they must be getting stored somewhere.
Sir can you tell how to do same thing with plotly module
thank you
How can I change canvas size ? I need smaller canvas and graph. Thanks
Excellent. Thank you for sharing your knowledge. Could I suggest a follow-up video whereby the matplotlib graph is animated?
Extremely helpful… Thank you for taking the time to make this!
I need to convert a python program source code to its exe using pyinstaller or auto py to exe but it always gives me error while converting of modules not found using–one file option
Using–one dir the exe works
Can you help me out
I am actually trying to convert an open source app available on github need to modify it and pack it back again into exe
Nice