Tkinter draw rectangle not working as expected

Viewed 176
WIDTH = HEIGHT = 800
DIMENSION = 8
SQ_SIZE = HEIGHT / DIMENSION
IMAGES = {}


def draw_board():
    colors = ["white", "black"]
    for r in range(DIMENSION+1):
        for c in range(DIMENSION+1):
            canvas.create_rectangle(100, 100, r * (WIDTH / DIMENSION), c * (WIDTH / DIMENSION), fill=colors[((r+c)%2)])


def load_images():
    pass


if __name__ == "__main__":
    root = Tk()
    root.resizable(False, False)
    canvas = Canvas(root, width=WIDTH, height=HEIGHT)
    draw_board()
    canvas.pack()
    root.mainloop()

the goal is draw a checkerboard for chess. if I do it without the fill argument it works as expected but when I add the fill option its either all black, or white(depending on how I arrange the colors in the colors array.)

how can I solve this without hardcoding every single square?

PS: I tested the colors[((r+c)%2)] by printing it and it works as expected

2 Answers

The problem isn't with the color, the problem is that you're drawing every square starting at 100,100. You add a white square at 100,100. Then you add a black square at 100,100 which hides the white square. Then you add white square that hides the black square, and a black square that hides the white square, and so on. The last square you draw is white, and it covers the whole screen.

To visualize what is happening, you can add periodic updates in your code. For example:

from tkinter import *
import time

WIDTH = HEIGHT = 800
DIMENSION = 8
SQ_SIZE = HEIGHT / DIMENSION
IMAGES = {}


def draw_board():
    colors = ["white", "black"]
    for r in range(DIMENSION+1):
        for c in range(DIMENSION+1):
            canvas.create_rectangle(100, 100, r * (WIDTH / DIMENSION), c * (WIDTH / DIMENSION), fill=colors[((r+c)%2)])
            root.update()
            time.sleep(.5)

if __name__ == "__main__":
    root = Tk()
    canvas = Canvas(root, width=WIDTH, height=HEIGHT, bg="bisque")
    canvas.pack()
    draw_board()
    root.mainloop()

Notice the addition of the call to update and sleep inside the loop. I also called pack on the canvas before calling draw_board. You can clearly see that the colors are alternating, but each square is hiding the previous square.

What you need to do is adjust the starting x,y coordinate for every square. For example:

for r in range(DIMENSION):
    for c in range(DIMENSION):
        x0, y0 = c*100, r*100
        x1, y1 = x0 + 100, y0 + 100
        canvas.create_rectangle(x0, y0, x1, y1, ...)

This is my first answer on stack overflow, I think you have misunderstood the working of create_rectangle.The syntax is

create_canvas(startX,startY,endX,endY,outline,fill)

and the answer you asked is below

canvas.create_rectangle(

        (r-1) * (WIDTH / DIMENSION),

        (c- 1) * (WIDTH / DIMENSION),

        r * (WIDTH / DIMENSION),

        c *(WIDTH / DIMENSION), 
        fill=colors[(r+c)%2])
Related