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

如何使Tkinter按钮拉伸填满所在的整个Frame容器?

解决Tkinter按钮无法填满Frame容器的问题

问题出在你只给按钮设置了sticky="nsew",但没有为按钮所在的Frame配置内部行和列的权重。Tkinter的grid布局中,sticky属性只是让组件填充它所在的单元格,但如果单元格本身不会随Frame的拉伸而扩展,按钮自然无法填满整个Frame。

你需要在创建按钮后,为Frame的第0行和第0列设置weight=1,让Frame内部的单元格能分配到拉伸的空间。修改后的代码如下:

import tkinter as tk

window = tk.Tk()

for i in range(3):
    for j in range(3):
        window.columnconfigure(i, weight=1, minsize=50)
        window.rowconfigure(j, weight=1, minsize=50)
        frame = tk.Frame(relief=tk.RAISED, borderwidth=3, padx=5, pady=5)
        frame.grid(row=i, column=j, sticky="nsew")
        # 为Frame的行和列设置权重,让内部单元格随Frame拉伸
        frame.rowconfigure(0, weight=1)
        frame.columnconfigure(0, weight=1)
        but = tk.Button(text=f"row {i+1}\n column {j+1}", master=frame)
        but.grid(row=0, column=0, sticky="nsew")
window.mainloop()

这样修改后,当你调整窗口大小时,每个Frame会填满所在的网格单元格,而按钮也会随之填满整个Frame容器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 02:45:40