2
from tkinter import Tk
import matplotlib
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

matplotlib.use('TkAgg')

root_win = Tk()
root_win.title('matplotlib in tkinter')

fig = Figure(figsize = (5, 4), dpi = 100)
plot = fig.add_subplot(1, 1, 1)
plot.plot([1, 2, 3])

canvas = FigureCanvasTkAgg(fig, master = root_win)
canvas.draw()

canvas.get_tk_widget().grid(row = 0, column = 0)

'''

If use 'grid' geometry manager in canvas, when I add the toolbar below appear : _tkinter.TclError: cannot use geometry manager pack inside . which already has slaves managed by grid so I must use 'pack' geometry manager.

canvas.get_tk_widget().pack(side = 'top', fill = 'both', expand = 1)

Use 'pack' geometry manager, add the toolbar correct.

'''

toolbar = NavigationToolbar2Tk(canvas, root_win)
toolbar.update()
canvas.get_tk_widget().pack(side = 'top', fill = 'both', expand = 1)


root_win.mainloop()

'''

Can I use 'grid' geometry manager for toolbar by other way?

'''

1 Answer 1

2

If you want to use the grid geometry manager with NavigationToolbar2Tk you need to use pack_toolbar=False.

toolbar = NavigationToolbar2Tk(canvas, root_win, pack_toolbar=False)
self.toolbar.update()
self.toolbar.grid(row = 0, column = 0)

I was having the same problem. Checking out the error code I got:

  File "filepath\lib\site-packages\matplotlib\backends\_backend_tk.py", line 535, in __init__
    self.pack(side=tk.BOTTOM, fill=tk.X)

Tkinter is defaulting to pack for the navigation toolbar. Check out the docs for Tk embedding here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.