Home > Mobile >  What is the proper way to set the size of a canvas in Tkinter?
What is the proper way to set the size of a canvas in Tkinter?

Time:10-06

I'm trying to build a simple GUI in Tkinter and I'm having trouble with placing a frame and a canvas beside each other. The canvas seems to take up more space than the width and height that have been specified.

Example code:

root = tk.Tk()
parent = tk.Frame(root)
parent.grid()
parent.master.geometry('400x400')
canvas = tk.Canvas(parent, width=200, height=400, relief='raised', borderwidth=5)
canvas.grid(row=0, column=0, sticky='nsew')
frame = tk.Frame(parent, width=200, height=400, relief='raised', borderwidth=5)
frame.grid(row=0, column=1, sticky='nsew')
parent.mainloop()

This gives this result:

Canvas and Frame in same window

You can see that the canvas has pushed the frame outside the window

However, when its just the frame, the frame fits nicely within the window:

enter image description here

When it's just the canvas the canvas pushes outside the window:

enter image description here

What is causing this difference in sizing and how do I handle it? Is there a proper way to set the size of a canvas?

CodePudding user response:

In addition to the width parameter, there are two other parameters that control the width of a canvas: borderwidth and highlightthickness. Both of those may have non-zero default values, depending on your platform.

In addition, the geometry manager may also contribute to the width and height depending on options and other factors.

To get a canvas that is precisely 200 pixels wide and 400 pixels tall, set the other values to zero, and don't use geometry manager options that may restrict or expand the size of the widget.

canvas = tk.Canvas(root, width=200, height=400, borderwidth=0, highlilghtthickness=0)
  • Related