In the following, the buttons labelled \'ONE\', \'TWO\', and \'THR\' do not get evenly spaced out. It seems to me that the root of the problem is that Tk is assuming a defau
old post I know, but I also struggled to get the columns and rows to maintain a common width/height so I thought I would share my solution
newish to python and tkinter, so if there are any mistakes please let me know
I created a grid manager, this allowed the main window and any frame to be setup with evenly spaced columns and rows, it's not 100% but for what I was using it for it worked well, it was especially useful during the building phase
one downside when creating a frame is the maximum number of rows/columns of the frame must be equal to or less than the number or rows/columns it is spanning, otherwise it goes a bit weird (nut sure why)
hope this helps
import tkinter
class grid_manager:
def __init__(self, Frame, colour = "gray94"):
self.Frame = Frame
self.Colour = colour
def set_grid(self, numofRows, numofColumns, borderwidth = 1):
self.numofRows = numofRows
self.numofColumns = numofColumns
self.borderwidth = borderwidth
for i in range(numofRows):
for j in range(numofColumns):
canvas = tkinter.Canvas(self.Frame)
canvas.config(relief="raised", borderwidth=self.borderwidth) #comment out to hide grid layout
canvas.grid(row=i, column=j)
canvas.config(background=self.Colour)
self.Frame.columnconfigure(j, weight=1)
self.Frame.rowconfigure(i, weight=1)
mainwindow = tkinter.Tk()
mainwindow.title("Test")
mainwindow.geometry("640x480-8-200")
mainGrid = grid_manager(mainwindow)
mainGrid.set_grid(10, 10)
header_Frame = tkinter.Frame(mainwindow)
header_Frame.grid(row=0, column=0, columnspan=10, sticky="nsew")
headerGrid = grid_manager(header_Frame)
headerGrid.set_grid(numofRows=1, numofColumns=10, borderwidth=5)
footerFrame = tkinter.Frame(mainwindow)
footerFrame.grid(row=9, column=0, columnspan=10, sticky="nsew")
footerGrid = grid_manager(footerFrame, "red")
footerGrid.set_grid(numofRows=1, numofColumns=10, borderwidth=5)
rightFrame = tkinter.Frame(mainwindow)
rightFrame.grid(row=1, column=5, rowspan=5, columnspan=5, sticky="nsew")
rightGrid = grid_manager(rightFrame, "blue")
rightGrid.set_grid(numofRows=5, numofColumns=5, borderwidth=2)
leftFrame = tkinter.Frame(mainwindow)
leftFrame.grid(row=3, column=0, rowspan=5, columnspan=4, sticky="nsew")
leftGrid = grid_manager(leftFrame, "yellow")
leftGrid.set_grid(numofRows=5, numofColumns=4, borderwidth=2)
mainwindow.mainloop()
enter image description here