[ACCEPTED]-Python Tkinter Embed Matplotlib in GUI-tkinter-canvas

Accepted answer
Score: 23

You don't have any other widgets so it's 46 hard to know where you want other widgets. Here's 45 what I can tell you though: by doing dataPlot.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) you 44 are asking Tkinter to fill the screen with 43 the plot. This, because you ask it to fill 42 in all directions (fill=BOTH) and expand to fill 41 any extra space (expand=1).

However, you can still 40 add other widgets. pack works by putting widgets 39 on one side of a container. Your container, master, always 38 has four sides. So, for example, if you 37 wanted to create a toolbar you would do 36 something like:

toolbar = tk.Frame(master)
button = tk.Button(toolbar, text="Push me")
button.pack(side="left") # left side of parent, the toolbar frame
toolbar.pack(side=TOP, fill="x") # top of parent, the master window

Notice that if you put this 35 code after the code where you pack the plot, the 34 toolbar shows up on the bottom! That's because 33 TOP, BOTTOM, etc refer to space left over by any 32 other widgets that have already been packed. The 31 plot takes up the top, the space left over 30 is at the bottom. So when you specify TOP again 29 it means "at the top of the area below 28 whatever is already at the top".

So, you 27 have some choices. The best choice is to 26 make your widgets in the order you wish 25 them to appear. If you pack the toolbar at the 24 top before you pack the plot, it will be the 23 toolbar that shows up at the very top. Further, you 22 can place the plot at the bottom rather 21 than the top and that will solve the problem, too.

By 20 the way, I typically create my widgets in 19 one block, then lay them all out in a separate 18 block. I find it makes the code easier to 17 maintain.

Another choice which may fit your 16 mental model better is to grid instead of pack. With grid you 15 can choose the row(s) and column(s) that 14 the widget occupies. This makes it easy 13 to lay things out in a grid, but at the 12 expense of having to use a little more code.

For 11 example, to put the toolbar at the top and 10 the plot down below you might do:

toolbar.grid(row=1, column=1, sticky="ew")
dataPlot.get_tk_widget().grid(row=1, column=1, sticky="nsew")
master.grid_rowconfigure(0, weight=0)
master.grid_rowconfigure(1, weight=1)
master.grid_columnconfigure(0, weight=1)

Notice 9 that rows and columns start at zero. Also, "weight" refers 8 to how much this widget expands relative 7 to other widgets. With two rows of equal 6 weight, they will expand equally when the 5 window is resized. A weight of zero means 4 no expansion. A weight of 2 for one row, and 3 1 for another means that the former will 2 expand twice as much as the latter.

For more 1 information see this page on grid, and this page on pack.

More Related questions