Home > Software engineering >  Python Tkinter column stretch to window height
Python Tkinter column stretch to window height

Time:02-15

I am trying to make an app that has multiple labels equally divided on columns

Here is my code:

import tkinter as tk

class Gui(tk.Tk):
def __init__(self, parent):
    tk.Tk.__init__(self, parent)
    self.parent = parent

    self.initialize()

def initialize(self):
    self.grid()
    self.geometry("1000x900")
    self.attributes('-alpha', 1)

    label = tk.Label(self, anchor="center", bg="green")
    label.grid(column=0, row=0, sticky='EW')

    label2 = tk.Label(self, anchor="center", bg="black")
    label2.grid(column=1, row=0, sticky='EW')

    label3 = tk.Label(self, anchor="center", bg="red")
    label3.grid(column=2, row=0, sticky='EW')

    self.grid_columnconfigure(0, weight=1)
    self.grid_columnconfigure(1, weight=1)
    self.grid_columnconfigure(2, weight=1)
    self.grid_rowconfigure(0, weight=1)

When running this i get the following window: enter image description here

When resizing the window the labels stretch to fit the window width, but not the height.

My goal is to have N = 3 (int this example) columns that occupy the whole window and stretch accordingly when resizing the window

What am i doing wrong?

CodePudding user response:

The sticky parameter of grid method is also responsible for stretching. You set edges of a grid cell to which your widget will stick. If you stick to the opposite edges and then resize the window it results in stretching your widgets.

So if you would like to stretch all directions use 'nsew' which are North, South, East and West.

    label = tk.Label(self, anchor="center", bg="green")
    label.grid(column=0, row=0, sticky='nsew')

    label2 = tk.Label(self, anchor="center", bg="black")
    label2.grid(column=1, row=0, sticky='nsew')

    label3 = tk.Label(self, anchor="center", bg="red")
    label3.grid(column=2, row=0, sticky='nsew')

Check this material for more: http://tkdocs.com/tutorial/grid.html#incell

CodePudding user response:

 sticky='NEWS' 

insted of

sticky="EW"

did the trick

  • Related