Search code examples
python-3.xtkinter

Widgets Positioned With Grid Do Not Show Unless I use Pack Buy Not Supposed to Use Grid and Pack in Same Class?


In the code below if I do not use pack() the widgets do not show but grid and pack are not supposed to be used in the same class. How to write this correctly without using pack?

#!/usr/bin/python3.9

import tkinter as tk
from tkinter import ttk


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

        pad={'padx': 40, 'pady': 80}

        # login button
        login_button = ttk.Button(self, text="Login")
        login_button.grid(column=0, row=0, **pad)

        login_button = ttk.Button(self, text="Login")
        login_button.grid(column=1, row=0, **pad)

        login_button = ttk.Button(self, text="Login")
        login_button.grid(column=2, row=0, **pad)

        login_button = ttk.Button(self, text="Login")
        login_button.grid(column=3, row=0, **pad)

        self.pack()

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

        self.geometry("1200x800")
        self.title('Login')
        self.resizable(0, 0)

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

Solution

  • self.pack() is calling on the instance of MainFrame which its parent is the root window. Whereas the other .grid(...) are calling on widgets inside that frame. Therefore they are not in same container.

    It is better not to call self.pack() inside the class method because how to layout children is the job of the parent:

    if __name__ == "__main__":
        app = App()
        frame = MainFrame(app)
        frame.pack()   # call pack() or other layout function here
        app.mainloop()