tkinter Canvas window size

Alberto Vassena picture Alberto Vassena · Nov 24, 2016 · Viewed 10.5k times · Source

I need to know when the Canvas is resized (eg when the master frame gets maximized) the new Canvas window size. Unfortunately, if I try self.canvas['width'] it always seems to me I get back the width it had whenever I initialized it and not the current width. How do I get the current Canvas window dimensions?

Answer

Bryan Oakley picture Bryan Oakley · Nov 24, 2016

When you retrieve self.canvas['width'], you are asking tkinter to give you the configured width of the widget, not the actual width. For the actual width you can use .winfo_width().

If you want to know when the canvas is resized, you can add a binding to the <Configure> event on the widget. The event object that is passed to the binding has a width attribute which also has the actual width of the widget.

Here's an example:

import tkinter as tk

root = tk.Tk()
canvas = tk.Canvas(root, width=200, height=200, background="bisque")
canvas.pack(side="bottom", fill="both", expand=True)

canvas.create_text(10, 30, anchor="sw", tags=["event"])
canvas.create_text(10, 30, anchor="nw", tags=["cget"])

def show_width(event):
    canvas.itemconfigure("event", text="event.width: %s" % event.width)
    canvas.itemconfigure("cget", text="winfo_width: %s" % event.widget.winfo_width())

canvas.bind("<Configure>", show_width)

root.mainloop()