Home > Net >  Tkinter make a frame fill whole column
Tkinter make a frame fill whole column

Time:12-05

I'm trying to create a simple GUI using Tkinter module. I have a layout consisting of two columns (with weights 1 and 2). Now, I'd like my two widgets that I add (cfg and cfgx) to fill up the whole column in which they are placed. How could I achieve such a thing with my current setup? Thanks in advance

import tkinter as tk
from components.ConfigCreator import ConfigCreator

WIDTH = 800
HEIGHT = 600
POS_X = 300
POS_Y = 200
class MainApplication(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        # root
        self.parent = parent

        self._setup_size_and_positioning()
        self._setup_layout()
        self._setup_widgets()

    def _setup_size_and_positioning(self) -> None:
        self.winfo_toplevel().title('Test app')
        self.winfo_toplevel().geometry(f"{WIDTH}x{HEIGHT} {POS_X} {POS_Y}")
        self.config(width=WIDTH, height=HEIGHT)

    def _setup_layout(self) -> None:
        self.grid(row=0, column=0)
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=2)

    def _setup_widgets(self) -> None:
        cfg = ConfigCreator(self)
        cfg.grid(row=0, column=0)
        cfg.config(bg="limegreen")

        cfgx = ConfigCreator(self)
        cfgx.grid(row=0, column=1)
        cfgx.config(bg="skyblue")
    

        

if __name__ == "__main__":
    root = tk.Tk()
    MainApplication(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

@edit

#ConfigCreator.py

import tkinter as tk

class ConfigCreator(tk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)

CodePudding user response:

You've configured the weight on the columns, but you haven't given any weight to any rows. Because of that, and because the frames by default are only 1 pixel tall, the columns will be virtually invisible.

To fix this you can give non-zero weight to one or more rows. For example, self.rowconfigure(0, weight=1)

You also haven't configured the contents in each column to fill the space allocated. You should add sticky="nsew" to get each of the inner frames to expand to fill. For example, cfg.grid(row=0, column=0, sticky="nsew")

screenshot

  • Related