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

Tkinter中pack_propagate(0)不生效:Frame为何仍适配子组件?

Tkinter Frame固定宽高失效问题解决

核心错误原因

你写的self.f1.pack_propagate=0是错误的——pack_propagate是Tkinter组件的方法,不是可直接赋值的属性,必须通过函数调用的方式传入参数,正确写法是self.f1.pack_propagate(0)。

为什么原代码不生效?

当你直接给pack_propagate赋值为0时,只是给这个Frame对象添加了一个自定义属性,根本没有调用到Tkinter内置的禁止尺寸传播方法,所以Frame依然会根据子组件(Label)的尺寸自动调整。

修正后的代码

import tkinter as tk
from tkinter import ttk

class MainWindow:
    def __init__(self):
        self.parent=tk.Tk()
        self.parent.geometry("830x590+370+100")
        self.parent.title("TEST")
        self.parent.minsize(830, 590)

        self.pw=ttk.PanedWindow(self.parent, orient=tk.HORIZONTAL)
        self.f1=tk.Frame(self.pw, background="white", width=200)
        self.f1.pack_propagate(0)  # 正确调用方法,禁止尺寸传播
        self.f2=tk.Frame(self.pw, background="white")
        self.pw.add(self.f1, weight=0)
        self.pw.add(self.f2, weight=1)
        self.pw.pack(fill=tk.BOTH, expand=True)

        self.label=tk.Label(self.f1, borderwidth=0, background="red", text="HELLO")
        self.label.pack(fill=tk.BOTH)   

        self.parent.mainloop()
    
app=MainWindow()

额外说明

  • pack_propagate(0)的作用是禁止Frame根据子组件的尺寸自动调整自身大小,强制使用你设置的width和height参数。
  • 你给PanedWindow设置的weight=0是正确的,这会让f1保持固定宽度,不会被PanedWindow拉伸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:52:06