'Use matplotlib menu bar in a tkinter GUI [duplicate]
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:
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:
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 1:[1]
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()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Domarm |


