1

I'm trying to make a simple chess board using tkinter, but between each row there is a bit of blank space that's not used even when expanding. The problem seems to be coming from configuring the columns and rows but I need that for the size to stay the same. How do I fix this? Here's my code:

from tkinter import *
import tkinter as tk

window = tk.Tk()

for i in range(8):
    window.columnconfigure(i, minsize=75)
    window.rowconfigure(i, minsize=75)
    for j in range(8):
        if i % 2 == 1 and j % 2 == 1:
            frame = tk.Frame (
                master=window,
                bg="white", 
                )
            frame.grid(row=i, column=j)
            label = tk.Label(master=frame, text="White sq", background="white", foreground="white")
            label.pack(padx=12, pady=15)
        elif i % 2 == 1 and j % 2 == 0:
            frame = tk.Frame (
                master=window,
                bg="black", 
                )
            frame.grid(row=i, column=j)
            label = tk.Label(master=frame, text="Black sq", background="black")
            label.pack(padx=12, pady=15)
        elif i % 2 == 0 and j % 2 == 1:
            frame = tk.Frame (
                master=window,
                bg="black", 
                )
            frame.grid(row=i, column=j)
            label = tk.Label(master=frame, text="Black sq", background="black")
            label.pack(padx=12, pady=15)
        else:
            frame = tk.Frame (
                master=window,
                bg="white", 
                )
            frame.grid(row=i, column=j)
            label = tk.Label(master=frame, text="White sq", background="white", foreground="white")
            label.pack(padx=12, pady=15)
        
            
            
        

window.mainloop()
Zayna
  • 11
  • 1

1 Answers1

0

As @acw1668 said, you can solve the problem by passing sticky="nswe" argument to grid.

Also, don't repeat yourself (DRY). You have copy-pasted almost the same stuff multiple times.

Here is the fixed code:

import tkinter as tk


root = tk.Tk()

fill_with_white = True

for row in range(8):
    root.rowconfigure(row, minsize=75)
    
    for column in range(8):
        bg = "white" if fill_with_white else "black"

        root.columnconfigure(column, minsize=75)
        frame = tk.Frame(root, bg=bg)
        frame.grid(row=row, column=column, sticky="news")
        label = tk.Label(frame, text=bg.capitalize(), bg=bg)
        label.pack()

        fill_with_white = not fill_with_white

    fill_with_white = not fill_with_white

root.mainloop()
TheLizzard
  • 7,248
  • 2
  • 11
  • 31
Demian Wolf
  • 1,698
  • 2
  • 14
  • 34