13

This is the most easy example.

#py3
from tkinter import *
tk = Tk()
canvas = Canvas(tk, width= 500 , height = 400)
canvas.winfo_height()
#In [4]: canvas.winfo_height()
#Out[4]: 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
YourTeddy
  • 413
  • 2
  • 5
  • 8

2 Answers2

13

If it doesn't work by using pack() function, you can try to add canvas.update() after using canvas.pack().

Jutta
  • 513
  • 5
  • 13
12

You have to pack the canvas element in the window before getting it's height. The height return is the actual height.

>>> from tkinter import * 
>>> tk = Tk()
>>> canvas = Canvas(tk, width= 500 , height = 400)
>>> canvas.winfo_height()
1
>>> canvas.pack()
>>> canvas.winfo_height()
402
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
  • 9
    To be a bit more pedantic, you have to make it visible, which you can do with pack, place, grid, or by embedding it in a text widget or canvas. And you have to have the window drawn on screen either via a call to `update` or by letting `mainloop` do its job. – Bryan Oakley Jan 20 '15 at 19:17
  • Completely an edge case, but I had an issue with getting the winfo_width on a frame that had child widgets deleted and that the geometry manager had re-sized the frame. Using bbox solved the issue as it was still able to get the size before and after the geometry resize of the frame. – Mattamue May 03 '21 at 02:13