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

Tkinter技术问题:如何在grid布局中居中第二个Frame

Tkinter grid布局实现Frame居中解决方案

问题原因

仅给第0列设置weight=1,新增的第2列未配置权重,导致水平方向额外空间全部分配给第0列,将中间第1列(frame2所在列)挤向右侧。

解决方法

为第0列和第2列设置相同的weight=1,让它们平分水平额外空间,中间列会自动居中;同时保留第0行的weight=1,确保frame2固定在窗口底部。

修改后的代码

from tkinter import ttk
import tkinter as tk

root = tk.Tk()

root.geometry('600x400+500+250')
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
root.grid_columnconfigure(2, weight=1)

frame1 = tk.Frame(root, bg='red', width=50, height=50)
frame2 = tk.Frame(root, bg='green', width=50, height=50)
frame3 = tk.Frame(root, bg='blue', width=50, height=50)

frame1.grid(row=0, column=0, sticky='NW')
frame2.grid(row=1, column=1, sticky='S')
frame3.grid(row=0, column=2, sticky='NE')

tk.mainloop()

说明

  • weight参数控制行/列对窗口额外空间的分配比例,列0和列2权重相等时,会平分水平空余空间,中间列自然居中。
  • 第0行设weight=1,使其占据大部分垂直空间,让第1行的frame2固定在底部。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:45:45