What does 'weight' do in tkinter?
Solution 1:
In the simplest terms possible, a non-zero weight causes a row or column to grow if there's extra space. The default is a weight of zero, which means the column will not grow if there's extra space.
Consider the following code, which creates a window larger than the widgets that are inside, and for which no columns have weight:
import tkinter as tk
root = tk.Tk()
root.geometry("200x100")
f1 = tk.Frame(root, background="bisque", width=10, height=100)
f2 = tk.Frame(root, background="pink", width=10, height=100)
f1.grid(row=0, column=0, sticky="nsew")
f2.grid(row=0, column=1, sticky="nsew")
root.grid_columnconfigure(0, weight=0)
root.grid_columnconfigure(1, weight=0)
root.mainloop()
This is what the window looks like:
The reason it looks that way is because tkinter has been told not to give any of the columns any extra space, so the extra space goes unused to the right.
Now, change the code so that we give a weight to just one column:
root.grid_columnconfigure(0, weight=1)
When we restart, we now have a window that looks like this:
What happened? Because column zero had a weight of one, tkinter gave the extra space to this column. You could have set the weight to 1, 100, 100000 and you would get the same result. In this case, all of the extra space goes to this one column.
What happens if you give both columns a weight? The extra space is divided between the columns proportional to their weight. For example, let's say you want a navigation area on the left that takes up 1/4 of the screen and the main area should take up 3/4 of the screen (a 1:3 ratio).
Let's change the weights to look like this:
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(1, weight=3)
Since both columns have weight, extra space is given to both columns. For every four pixels of extra space, column 0 will get 1 and column 1 will get the other 3.
What's more, if you interactively resize the window, the proportion is preserved as much as possible. Here's the same window that I manually resized to be much wider: