问题
I'm developing a small Tkinter GUI to draw matplotlib-plots. (It contains a few Entries and assembles the plot according to their content.)
I have designed my plotting widget according to http://matplotlib.org/examples/user_interfaces/embedding_in_tk.html, only I use grid instead of pack:
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(row=1,column=4,columnspan=3,rowspan=20)
That part works. But embedding the NavigationToolbar in the same fashion does not. Tkinter breaks down without error when I include the lines:
toolbar = NavigationToolbar2TkAgg( canvas, root )
canvas._tkcanvas.grid(row=22,column=4)
I know this is because NavigationToolbar calls pack internally, and pack and grid don't get along. However, I like grid and would hate to have to redesign my whole GUI just to be able to use the NavigationToolbar.
Is there a workaround so I can use NavigationToolbar2TkAgg via grid? (I have found the advice to "subclass and overload" here, but don't know how to do that.)
Any help greatly appreciated!
回答1:
Can you create an empty frame, then put the NavigationToolbar in that frame? I assume the NavigationToolbar will then pack itself in that frame. You can then use grid on the frame.
回答2:
Here is a code example for what was mentioned in Bryan Oakleys answer (add toolbar to frame, place frame on grid):
fig = Figure(figsize=(5, 5), dpi=100)
canvas = FigureCanvasTkAgg(fig, master=root)
canvas.get_tk_widget().grid(row=1,column=4,columnspan=3,rowspan=20)
# here: plot suff to your fig
canvas.draw()
############### TOOLBAR ###############
toolbarFrame = Frame(master=root)
toolbarFrame.grid(row=22,column=4)
toolbar = NavigationToolbar2TkAgg(canvas, toolbarFrame)
来源:https://stackoverflow.com/questions/12913854/displaying-matplotlib-navigation-toolbar-in-tkinter-via-grid