How to embed Matplotlib charts in Tkinter GUI?
Prerequisite: Introduction to Tkinter | Introduction to Matplotlib
When Matplotlib is used from Python shell, the plots are displayed in a default window. The plots can be embedded in many graphical user interfaces like wxpython, pygtk, or Tkinter. These various options available as a target for the output plot are referred to as ‘backends‘. There are various modules available in matplotlib.backend for choosing the backend. One such module is backend_tkagg which is useful for embedding plots in Tkinter.
Creating the Tkinter Application :
First, let us create a basic Tkinter application with the main window and one button which can be used to display the plot.
Python3
from tkinter import *
window = Tk()
window.title( 'Plotting in Tkinter' )
window.geometry( "500x500" )
plot_button = Button(master = window,
height = 2 ,
width = 10 ,
text = "Plot" )
plot_button.pack()
window.mainloop()
|
Output :
Embedding the Plot:
First, we need to create the figure object using the Figure() class. Then, a Tkinter canvas(containing the figure) is created using FigureCanvasTkAgg() class. Matplotlib charts by default have a toolbar at the bottom. When working with Tkinter, however, this toolbar needs to be embedded in the canvas separately using the NavigationToolbar2Tk() class.
In the implementation below, a simple graph for:
is plotted. The plot function is bound to a button that displays the figure when pressed.
Python3
from tkinter import *
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg,
NavigationToolbar2Tk)
def plot():
fig = Figure(figsize = ( 5 , 5 ),
dpi = 100 )
y = [i * * 2 for i in range ( 101 )]
plot1 = fig.add_subplot( 111 )
plot1.plot(y)
canvas = FigureCanvasTkAgg(fig,
master = window)
canvas.draw()
canvas.get_tk_widget().pack()
toolbar = NavigationToolbar2Tk(canvas,
window)
toolbar.update()
canvas.get_tk_widget().pack()
window = Tk()
window.title( 'Plotting in Tkinter' )
window.geometry( "500x500" )
plot_button = Button(master = window,
command = plot,
height = 2 ,
width = 10 ,
text = "Plot" )
plot_button.pack()
window.mainloop()
|
Output :
Last Updated :
10 Jul, 2020
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...