Chris Irwin
Chris Irwin

Reputation: 117

tkinter canvas in grid has extra space

I have a canvas inside a frame and I've said the canvas should be 250x250. But for some reason it is being created bigger, with extra space on the right and bottom. Here's my code... any ideas?

from tkinter import *
from tkinter import ttk
from player import player0

alpha = ('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z')

class GUI(Frame):

    def __init__(self, master):
        Frame.__init__(self, master)
        self.boardsize = 250
        self.sqsize = self.boardsize//5
        master.title("Canvas with extra space")
        self.initialdraw()
        self.grid(row=0,column=0)

    def initialdraw(self):
        mainframe = ttk.Frame(self, padding=(5,5,5,5))
        mainframe.grid(column=0, row=0, sticky=(N, S, E, W))

        self.board = Canvas(mainframe, width=self.boardsize, height=self.boardsize,bg='white')
        self.board.grid(row=1,column=0)

        for row in range(5):
            for col in range(5):
                top = row * self.sqsize
                left = col * self.sqsize
                bottom = row * self.sqsize + self.sqsize -2
                right = col * self.sqsize + self.sqsize -2
                rect = self.board.create_rectangle(left,top,right,bottom,outline='gray',fill='')

        self.board.focus_set()

if __name__ == '__main__':
    tk = Tk()
    gui = GUI(tk)
    tk.mainloop()

The result is this:

canvas with extra space

I would rather avoid the white gutter on the right and the bottom of the canvas after the smaller squares have been drawn.

Upvotes: 3

Views: 4899

Answers (2)

twasbrillig
twasbrillig

Reputation: 18821

I made these changes:

self.boardsize = 249
self.sqsize = 50#self.boardsize//5

and

top = row * self.sqsize +2
left = col * self.sqsize +2
bottom = row * self.sqsize + self.sqsize
right = col * self.sqsize + self.sqsize

It will draw correctly. You can see that the gray border lines are correct on all 4 sides:

enter image description here

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 385800

The canvas has a border, controlled by the borderwidth attribute. It also has another border controlled by the highlightthickness attribute. Set both of those to zero and your canvas should be exactly the size you set it to be.

The border attribute is typically used to provide a 3D effect -- a raised border, sunken boarder, or a couple other variations. The highlightthickness (and highlightcolor) attributes define a solid outline used to denote that the widget has the keyboard focus.

Upvotes: 5

Related Questions