David Ulloa
David Ulloa

Reputation: 21

.grid() isn't centering my widget by default in Tkinter (Python)

from tkinter import *
root = Tk()

equa = ""
equation = StringVar()

calculation = Label(root, textvariable = equation)

equation.set("23 + 54")

calculation.grid(columnspan = 4)

def btnPress(num):
    global equa
    equa = equa + str(num)
    equation.set(equa)

Button0 = Button(root, text = "0", command = lambda:btnPress(0))
Button0.grid(row = 1, column = 0)

Button1 = Button(root, text = "1", command = lambda:btnPress(1))
Button1.grid(row = 1, column = 1)

Button2 = Button(root, text = "2", command = lambda:btnPress(3))
Button2.grid(row = 1, column = 2)

root.mainloop()

Whenever I run my code, .grid() doesn't automatically center my buttons. I've read that .grid() is suppose to automatically center widgets, but I'm not sure if there is something that I'm doing wrong.

Upvotes: 1

Views: 7801

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385830

By default, the grid geometry manage only uses as much space as it needs, and no more. When you resize the window, all of the extra space goes unused unless you tell grid how to use it.

Rows and columns have a weight attribute which tells grid how to use extra space. Extra space is given to every row and/or column that has a positive weight. the weight is proportional, so a column with a weight of 2 will get twice as much extra space as a column of weight 1.

If you want the buttons to take up all extra space, give each column the same weight. If you want them to be centered, give weight to empty columns along the edges. The same goes for rows and extra vertical space.

You give give columns weight with the columnconfigure method of the master widget. In your case that is the root window.

Examples

To have the buttons evenly spaced, add the following lines of code:

root.grid_columnconfigure((0, 1, 2), weight=1)

enter image description here

If you want the buttons themselves to expand and fill the extra space, use the sticky attribute to cause them to stick to the edges of the columns:

Button0.grid(row = 1, column = 0, sticky="ew")
Button1.grid(row = 1, column = 1, sticky="ew")
Button2.grid(row = 1, column = 2, sticky="ew")

enter image description here

If you want the buttons to remain in the center, give all of the weight to empty columns with the following code:

calculation.grid(row=0, column=1, columnspan = 3)
Button0.grid(row=1, column=1, sticky="ew")
Button1.grid(row=1, column=2, sticky="ew")
Button2.grid(row=1, column=3, sticky="ew")
root.grid_columnconfigure((0, 4), weight=1)

enter image description here

Upvotes: 6

Related Questions