You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter Canvas组件无width/height属性,如何获取其宽高?

How to Get Tkinter Canvas Width and Height (Tkinter 8.5)

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 06:36:16