sgfw sgfw - 5 months ago 7
Python Question

In tkinter, the canvas size settings seem to stop working when the canvas is used as a master for another widget. Is there a way to get around this?

So, this is a simplified form of the problem I'm facing:

The following code produces a canvas whose size is just big enough to accomidate the label, even though it was configured to be 400 by 400

import tkinter as tk
root = tk.Tk()

canvas = tk.Canvas(root, width=400, height=400)
canvas.pack()

label = tk.Label(canvas, text='foo')
label.pack()


If the last two lines are omitted, then the canvas is the size that I would expect it to be (400 by 400), but it does not contain the label, which is something that I want it to contain.

As I said, this is a simplified form of my problem, I actually want to put several widgets into the canvas, but this behavior is the cause of my problem. Is there a way to make the canvas the size that I want (in pixels) and use it as the master for other widgets?

Answer

What you can do is setting the size of the root window:

import tkinter as tk
root = tk.Tk()
root.geometry('400x400')
canvas = tk.Canvas(root)
canvas.pack()

label = tk.Label(canvas, text='foo')
label.pack()

root.mainloop()

If you can use the grid method, using row/column configure and sticky argument will do the rest of the job. I don't know pack enough.

Comments