Tkinter Canvas组件无width/height属性,如何获取其宽高?
Hey there! I get it—you noticed Tkinter's Canvas doesn't have direct width or height attributes, which can be confusing at first. Luckily, there are two reliable ways to grab those values depending on what you need:
1. Get the actual rendered width/height
If you want the real-time size of the Canvas as it appears on screen (perfect since you already called root.update() to render it), use the winfo_width() and winfo_height() methods:
def draw_grid_lines(widget): width = widget.winfo_width() height = widget.winfo_height() # Use width and height here for current on-screen dimensions
These methods return the current pixel dimensions of the Canvas after it's been drawn. Just make sure the widget has been rendered (your root.update() call takes care of that!)—otherwise you might get 1 as a default value before the widget is displayed.
2. Get the configured width/height
If you need the original size you set when initializing the Canvas (regardless of any window resizing), use the cget() method to fetch the configuration values:
def draw_grid_lines(widget): width = widget.cget("width") height = widget.cget("height") # Convert to integers if you need numeric values: width_int = int(width) height_int = int(height)
This pulls the exact values you passed (or the default) when creating the Canvas with Canvas(root, bg=ocean, width=..., height=...).
Quick Tip
- Reach for
winfo_width()/winfo_height()when you care about how big the Canvas actually is right now (e.g., after the user resizes the window). - Use
cget()when you need the original configured size, even if the window has been adjusted.
内容的提问来源于stack exchange,提问作者L. Price

