terence vaughn
terence vaughn

Reputation: 537

How to use the grid() python

How can I use the grid() to place a widget at the bottom of a window? For example, this code will place these labels right under each other, but what if I want to move label_4 to the bottom of the window, or closer to the bottom, how is this accomplished?

label_1 = Label(text = 'Name 1').grid(row = 0, sticky = W)
label_2 = Label(text = 'Name 2').grid(row = 1, sticky = W)
label_3 = Label(text = 'Name 3').grid(row = 2, sticky = W)
label_4 = Label(text = 'Name 4').grid(row = 3, sticky = W)

Upvotes: 2

Views: 7969

Answers (1)

Peter Varo
Peter Varo

Reputation: 12150

If you want to use the grid system for this, you have to create a "spacer" cell in the grid system (an empty one), which can dynamically get the spaces left from the window, and pushes the last label to the bottom.

from Tkinter import *  # or tkinter if you use Python3

root = Tk()

label_1 = Label(master=root, text='Name 1')
label_2 = Label(master=root, text='Name 2')
label_3 = Label(master=root, text='Name 3')
label_4 = Label(master=root, text='Name 4')

label_1.grid(row=0)
label_2.grid(row=1)
label_3.grid(row=2)  # this is the 2nd
label_4.grid(row=4)  # this is the 4th

root.rowconfigure(index=3, weight=1)  # add weight to the 3rd!
root.mainloop()

But for this simple scenario, I think you should use pack instead of grid:

from Tkinter import *  # or tkinter if you use Python3

root = Tk()

label_1 = Label(master=root, text='Name 1')
label_2 = Label(master=root, text='Name 2')
label_3 = Label(master=root, text='Name 3')
label_4 = Label(master=root, text='Name 4')

label_1.pack()
label_2.pack()
label_3.pack()
label_4.pack(side=BOTTOM)

root.mainloop()

Upvotes: 2

Related Questions