Search code examples
pythoncanvastkinterchess

How to grid objects on a canvas in Tkinter?


I am currently working on creating a chess game in python using the class Tkinter. I am making the chessboard right now. Here is some example code of what I am doing:

board_canvas = tkinter.Canvas(mainWindow, borderwidth=1)
board_canvas.grid(row=1, column=0, sticky='ew', columnspan=8, rowspan=8)

x = 100
y = 100

a1 = board_canvas.create_rectangle(0, 0, x, y, fill='black')
a2 = board_canvas.create_rectangle(0, 0, x, y, fill='white')
a3 = board_canvas.create_rectangle(0, 0, x, y, fill='black') 

My question is how to grid my canvas objects so that they don't all just sit on top of each other. Or if that doesn't work, what is a better way that I can layout my chessboard?


Solution

  • Each rectangle has four coordinates(x0, y0, x1, y1: (x0, y0) is the top left corner, and (x1, y1) is the pixel outside the bottom right corner. So you just need to increment the x coordinate for the top left and bottom right for each square.

    import tkinter
    mainWindow =tkinter.Tk()
    
    board_canvas = tkinter.Canvas(mainWindow, borderwidth=1)
    board_canvas.grid(row=1, column=0, sticky='ew', columnspan=8, rowspan=8)
    
    x = 100
    y = 100
    
    a1 = board_canvas.create_rectangle(0, 0, x, y, fill='black')
    a2 = board_canvas.create_rectangle(100, 0, 200, y, fill='white')
    a3 = board_canvas.create_rectangle(200, 0, 300, y, fill='black')
    
    mainWindow.mainloop()
    

    Of course, for an entire chessboard, you would probably want to increment the values using a loop.