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

如何让Tkinter多Frame与主窗口同尺寸?configure方法无效

解决Tkinter中Frame无法与主窗口尺寸匹配的问题

问题原因

  1. ttk.Notebook的自动尺寸管理:你手动用configure(width=xxx, height=xxx)设置Frame尺寸无效,是因为Notebook组件会自动控制内部子Frame的尺寸,覆盖你手动设置的值。
  2. 多余的pack调用:你给每个Frame加了pack(fill=tk.BOTH, expand=True),但Frame的父容器是Notebook,Notebook会自己处理子组件的显示,这个pack操作完全没必要,反而可能干扰布局。

修改后的代码

import tkinter as tk
import tkinter.ttk as ttk

class Window:
    def __init__(self, master):
        self.master = master  

        self.master.title('MediaTools')  
        self.master.geometry("500x480") 
        
        # 让Notebook充满主窗口
        self.notebook = ttk.Notebook(self.master)
        self.notebook.pack(padx=5, pady=5, fill=tk.BOTH, expand=True)

        # Frame 1
        frame1 = ttk.Frame(self.notebook)
        label1 = ttk.Label(frame1, text="This is Window One")
        label1.pack(pady=50, padx=20)
        self.notebook.add(frame1, text="Validación de archivos")

        # Frame 2
        frame2 = ttk.Frame(self.notebook)
        label2 = ttk.Label(frame2, text="This is Window Two")
        label2.pack(pady=50, padx=20)
        self.notebook.add(frame2, text="Validación de información")

        # Frame 3
        frame3 = ttk.Frame(self.notebook)
        label3 = ttk.Label(frame3, text="Proceso")
        label3.pack(pady=50, padx=20)
        self.notebook.insert("end", frame3, text="Proceso")
 
root = tk.Tk()
window = Window(root)
root.mainloop()

改动说明

  • 把self.notebook.pack(...)移到创建Notebook之后,并且加上fill=tk.BOTH, expand=True,让Notebook完全填充主窗口的可用空间。
  • 移除所有Frame的pack()和configure(width/height)调用,Notebook会自动让内部Frame和自己尺寸保持一致,从而匹配主窗口大小。
  • 调整了代码结构,让每个Frame的创建和添加逻辑更清晰。

内容的提问来源于stack exchange,提问作者Julio Ortegón

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:13:33