pythontkintertkinter-layout

How to replace pack() with grid()


The following code enables the status bar to remain at the bottom of the window and expand to fill the window when the window is resized. How can I replace pack() with grid() to do the same thing?

import tkinter as tk
from tkinter import ttk

colour='blue'

class StatusBar(ttk.Frame):   
    def __init__(self, container):
        super().__init__(container) 

        self.columnconfigure(0, weight=1)
        self.rowconfigure(0,weight=1) 
    
        self.label=tk.Label(self, text="STATUS BAR")

        self.label.grid()

        self.pack(fill='x', expand=True, anchor='s')


class App(tk.Tk):
    
    def __init__(self):
        super().__init__()

        self.title('Replace')
        self.geometry('800x500')
        self.resizable(1, 1)
        self.configure(bg=colour)   


if __name__ == "__main__":
    
    app = App()
    sb = StatusBar(app)
    app.mainloop()

Solution

  • You can use .rowconfigure() and .columnconfigure() on app and .grid() on sb just like what you did inside StatusBar.__init__():

    class StatusBar(ttk.Frame):
        def __init__(self, container):
            ...
    
            #self.pack(fill='x', expand=True, anchor='s')
    
    ...
    
    if __name__ == '__main__':
        app = App()
    
        # allocate all available space to row 0 and column 0
        app.rowconfigure(0, weight=1)
        app.columnconfigure(0, weight=1)
    
        sb = StatusBar(app)
        # put sb on row 1 and column 0 and use sticky="ew"
        # then sb will be put at the bottom of the window and fill all the space horizontally
        sb.grid(row=1, column=0, sticky="ew")
    
        app.mainloop()