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

Tkinter中窗口大小由Frame对象决定时如何获取应用实际尺寸?

问题原因

你调用winfo_width()返回1是因为执行打印代码时,root窗口还没有完成实际渲染,所有布局尺寸都未完成计算,只能拿到未初始化的默认值,winfo_reqwidth()返回的是组件申请的推荐尺寸,也不是渲染后的真实尺寸。


解决方法

方法1:强制刷新窗口后获取

在读取尺寸前调用root.update()强制tkinter完成所有布局、渲染计算,之后读取的尺寸就是实际生效的窗口尺寸:

import tkinter

root = tkinter.Tk()
tkinter.Frame(root, width=640, height=360, bg="gray").grid()

# 强制完成窗口全流程渲染
root.update()
print(root.winfo_width())  # 输出640,为实际窗口宽度
print(root.winfo_height()) # 输出360+系统标题栏高度,为实际窗口总高度

root.mainloop()

方法2:绑定事件动态获取

如果需要实时监听窗口尺寸变化(包括用户拖拽调整窗口的场景),可以绑定<Configure>事件,窗口尺寸每次变动时自动触发回调获取最新值:

import tkinter

def update_size(event):
    # 过滤子组件触发的事件,只处理root窗口的尺寸变动
    if event.widget == root:
        print(f"实时尺寸:宽{root.winfo_width()} 高{root.winfo_height()}")

root = tkinter.Tk()
tkinter.Frame(root, width=640, height=360, bg="gray").grid()

root.bind("<Configure>", update_size)
root.mainloop()

内容的提问来源于stack exchange,提问作者yui amanda

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:51:04