Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use matplotlib menu bar in a tkinter GUI

If i create a plot using this script

import matplotlib.pyplot as plt

fig, ax = plt.subplots()
ax.plot([1, 2, 3, 4], [1, 4, 5, 3])
plt.show()

I get this result:

Plot direct

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

At the top I get a menu bar with useful functionality like zooming, panning and saving the plot. If I create a plot in a canvas in a tkinter GUI like so

import tkinter as tk
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

window = tk.Tk()

fig = Figure(figsize=(5, 2), layout="constrained")
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4], [1, 4, 5, 3])
canvas = FigureCanvasTkAgg(fig)
canvas.draw()
canvas.get_tk_widget().pack()

window.mainloop()

I get this result:

Plot tkinter

It lacks this menu bar, but I would still like to use the functionality in a GUI. Is there a way to do that?

>Solution :

You have to create Toolbar manually using NavigationToolbar2Tk.

Here is the code snippet:

import tkinter as tk

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure

window = tk.Tk()

fig = Figure(figsize=(5, 2), layout="constrained")
ax = fig.add_subplot(111)
ax.plot([1, 2, 3, 4], [1, 4, 5, 3])
canvas = FigureCanvasTkAgg(fig)

toolbar = NavigationToolbar2Tk(canvas, window)
toolbar.update()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

canvas.draw()
canvas.get_tk_widget().pack(expand=1)

window.mainloop()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading