Get height/width of tkinter Canvas

Viewed 976

I am searching for this for ages now. Is it so hard to get the height/width of a Canvas in tkinter? I want to do something like this:

c = Tk.Canvas(self, heigth=12, width=12)
c.create_oval(0, 0, self.height, self.width)

So that I draw a circle with the circumference of the width/height of my canvas.

How come I can't find any attribute like width/height of that canvas? c.winfo_width and c.winfo_height wouldn't work, because that only gives me error.

Can you help me? This is really irritating, since even in the constructor there is the attribute heightand width...

2 Answers

Use winfo_reqwidth and winfo_reqheight:

root = tk.Tk()
c = tk.Canvas(root, height=120, width=120)
c.create_oval(0, 0, c.winfo_reqheight(), c.winfo_reqwidth())

c.pack()
root.mainloop()

You have to call <tkinter.Tk>.update and <tkinter.Canvas>.pack before the winfo_height like this:

import tkinter as tk

root = tk.Tk()
c = tk.Canvas(root, height=120, width=120)
c.pack()

root.update()
c.create_oval(0, 0, c.winfo_height(), c.winfo_width())

root.mainloop()

Also parts of this code are stolen from @hussic.

<tkinter.Tk>.update makes sure that all tkinter tasks are done. Those tasks can be things like making sure that the geometry manager was reserved the space for the widgets and the widgets are drawn on the screen. Calling <tkinter.Widget>.update where Widget can be any tkinter widget is the same as calling <tkinter.Tk>.update as it will call the same tcl function.

Related