water
water

Reputation: 113

matplotlib plot toolbar geometry manager in tkinter canvas question

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?

'''

Upvotes: 2

Views: 351

Answers (1)

Marquez Cordova
Marquez Cordova

Reputation: 91

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.

Upvotes: 2

Related Questions