1

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

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?

LukasFun
  • 171
  • 1
  • 4
  • 17

1 Answers1

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()
Domarm
  • 2,360
  • 1
  • 5
  • 17