Python grid columnspan Python grid columnspan tkinter tkinter

Python grid columnspan


When using grid, you need to tell tkinter how it should allocate extra space. Grid will distribute any extra space between rows and columns proportional to their "weight". For example, a column with a weight of 3 will get 3 times more extra space than a column with a weight of 1. The default weight of each row and column is zero, meaning it will not be given any extra space.

As a rule of thumb, whenever you use grid you should give a non-zero weight to at least one row and at least one column, so that any extra space does not go unused.

In your case, the widgets are placed in the root window, so you need to configure the weight of the rows and columns in the root window. Since you are only using one row and one column you can do it like this:

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

That's only part of the story. With that, tkinter will allocate extra space to the row and column that contains the text widget, but because you didn't tell it otherwise the widget will float in the middle of that row and column.

To fix that, you need to have the edges of the widget "stick" to the edges of the space given to it. You do that with the sticky attribute. In your specific case you would do it like this:

text.grid(row=0,column=0, sticky="nsew")

The values for sticky are the letters "n" (north), "s" (south), "e" (east), and "w" (west), or any combination.

Note that if you are only going to put a single widget within a window or frame, you can get the same effect with a single line of code:

text.pack(fill="both", expand=True)