python-3.xtkinter

widgets not filling entire frame using Tkinter


Here is my code -

import tkinter as tk
from tkinter import ttk
from tkinter import messagebox

root = tk.Tk()

root.title("Food shopping")
root.geometry('800x500')

root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)
# root.columnconfigure(2, weight=1)

root.rowconfigure(0, weight=1)
root.rowconfigure(1, weight=1)

# Blank space top left
frame1 = tk.Frame(root)
frame1.configure(bg='red')
frame1.grid(row=0, column=0, sticky='nswe', padx=5, pady=5)

# Frame containing the 4 buttons
frame2 = tk.Frame(root)
frame2.configure(bg='blue')
frame2.grid(row=0, column=1, sticky="nswe", padx=5, pady=5)

# Frame containing the first check boxes
frame3 = tk.Frame(root)
frame3.configure(bg='green')
frame3.grid(row=1, column=0, sticky="nswe", padx=5, pady=5)

entry_btn = ttk.Button(frame2, text="Add")
entry_btn.grid(row=0, column=0, sticky='we')

entry_btn2 = ttk.Button(frame2, text="Clear")
entry_btn2.grid(row=0, column=1, sticky='we')

entry_btn3 = ttk.Button(frame2, text="Continue")
entry_btn3.grid(row=0, column=2, sticky='we')

entry_btn4 = ttk.Button(frame2, text="Finish")
entry_btn4.grid(row=1, column=0, columnspan=3, sticky='we')

root.mainloop()

and this is what it produces

enter image description here

The only reason the frames are coloured is so i can clearly see them. Why are the buttons not filling the entire blue frame? and why is the blue frame bigger despite having the same weight as the other frames?


Solution

  • By default, grid will only use enough space to fit the natural size of the widgets. If you want a row or column to expand to use extra space you have to explicitly configure it that way.

    For example, if you want the two rows in the blue frame to take up the whole area, give them a weight of 1 with rowconfigure

    frame2.grid_rowconfigure((0,1), weight=1)
    

    Similarly, if you want the three columns to fill the space, use columnconfigure:

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