Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a element to stick to the bottom-right corner in Tkinter?

I put button on a frame like this in Tkinter for python3:

b2_1 = Button(frame1, text='aaaaaaaaaaaa')
b2_1.pack(pady=20, side=RIGHT)

b2_2 = Button(frame1, text='bbbbbbbbbbbbbbb')
b2_2.pack()

I want the buttons b2_1 and b2_2 to be stick not only to the right side, but also to the bottom, one right above another. How can I do that?

like image 954
Saurabh Avatar asked Dec 25 '16 17:12

Saurabh


2 Answers

The answer to "how do I put something in the bottom right corner?" can't be adequately answered out of context. It really depends on what else is in the window. You can use use place to easily place a widget anywhere you want, but it's rarely the right solution.

Grid is relatively easy to understand if you really do want to lay things out in a grid (eg: a right-most column with a couple rows on the bottom and one or more on top.

Pack can also be used, though it typically involves using additional frames. For example, you could create a frame for the left and right, and then pack the buttons at the bottom of the right frame.

There is also the possibility to use more than one along with additional frames. For example, you could use grid to lay out the main widget into a header, main area, and footer, and then use pack to arrange buttons in the footer.

If you literally only want two buttons, and you want them stacked in the bottom-right corner, I suggest using grid. In addition to placing them in a row on the bottom, you need to make sure that there is at least one other row and one other column that takes up any extra space. The rows and columns can be empty, but they must be configured to have a "weight".

For example:

frame1.grid_rowconfigure(0, weight=1)
frame1.grid_columnconfigure(0, weight=1)

# give the empty row 0 and column 0 a non-zero weight
# so that grid gives all extra space to those columns.

b2_1.grid(row=1, column=1)
b2_2.grid(row=2, column=1)
like image 123
Bryan Oakley Avatar answered Oct 22 '22 00:10

Bryan Oakley


pack is not the ideal geometry manager in this case. You use pack in a frame where you just want to stick children one after the other. There is also a place manager which I have yet to see a 'natural' use for.

In this case use the grid manager. This is less simple than pack but has the flexibility you want. Once you figure out how many rows and columns your grid will have, placing is simple with .grid(column=lastcol,row=lastrow). Terry Jan Reedy also suggested using way too big numbers since empty columns/rows are not displayed, but I like to be pedantic so I know how my grid looks like exactly.

like image 35
kabanus Avatar answered Oct 22 '22 00:10

kabanus