2

I am trying to draw a chessboard, but last elements are oversized. How can I solve this?

from tkinter import *

Form = Tk()
Form.title("H")
size = 50
arr = [[Button(Form, width=size, height=size) for j in range(8)] for i in range(8)]
for i in range(8):
    for j in range(8):
        if (i + j) % 2 == 0:
            arr[i][j].configure(bg='white')
        else:
            arr[i][j].configure(bg='black')
        arr[i][j].place(x=i * size, y=j * size)
Form.mainloop()

Launch result

Lksih
  • 23
  • 4

3 Answers3

2

You need to specify width and height keyword arguments when placing the buttons:

from tkinter import *

Form = Tk()
Form.title("H")
Form.geometry("400x400")
size = 50

arr = [[Button(Form, width=size, height=size) for i in range(8)] for j in range(8)]

for i in range(8):
    for j in range(8):
        color = 'black' if (i+j) % 2 else 'white'
        arr[i][j].configure(bg=color)
        arr[i][j].place(x=i*size, y=j*size, height=size, width=size)

Form.mainloop()

Result:

screenshot of what's displayed

martineau
  • 119,623
  • 25
  • 170
  • 301
0

Try this:

from tkinter import *

root = Tk()
root.geometry("300x300")
size = 5
arr = []
for i in range(8):
    root.grid_rowconfigure(i, weight=1)
    for j in range(8):
        root.grid_columnconfigure(j, weight=1)
        if (i + j) % 2 == 0:
            bg = "white"
        else:
            bg = "black"
        button = Button(root, bg=bg)
        button.grid(row=i, column=j, sticky="news")
        arr.append(button)
root.mainloop()

I change it so it uses .grid instead of .pack. That allows me to use row=i, column=j which is way simpler than what you did. Also copying this I was able to make the buttons expand to fit the window. I suggest that you create a frame for all of those buttons. Also it will be way easier if you used a single tkinter.Canvas instead of 64 tkinter.Buttons.

TheLizzard
  • 7,248
  • 2
  • 11
  • 31
0
from tkinter import *

root = Tk()

arr = [[Button(root) for j in range(8)] for i in range(8)]
for i in range(8):
    Grid.columnconfigure(root, i, weight=1, minsize=25)
    Grid.rowconfigure(root, i, weight=1)
    for j in range(8):
        Grid.columnconfigure(root, j, weight=1, minsize=25)
        Grid.rowconfigure(root, j, weight=1)
        if (i + j) % 2 == 0:
            arr[i][j].configure(bg='white')
            arr[i][j].grid(row= i, column= j, sticky= N+S+E+W)
        else:
            arr[i][j].configure(bg='black')
            arr[i][j].grid(row= i, column= j, sticky= N+S+E+W)


root.mainloop()
Davinder Singh
  • 2,060
  • 2
  • 7
  • 22