Displaying Matplotlib Navigation Toolbar in Tkinter via grid

耗尽温柔 提交于 2019-12-30 07:58:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!