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

Tkinter Notebook添加Treeview后无法铺满窗口问题求助

问题解决:Tkinter Notebook无法铺满主窗口

问题原因

问题出在两个关键设置上:

  • 给标签页的ttk.Frame设置了固定width和height,导致Notebook组件优先遵循框架的固定尺寸,而非自适应主窗口大小。
  • Notebook的pack方法仅设置了expand=True,缺少fill='both'参数,无法填充主窗口的全部可用空间。

修复步骤

  1. 移除框架固定尺寸:删除EntriesFrame和RaceFrame的width、height参数,让框架由内部组件和窗口尺寸自动调整。
  2. 调整Notebook的pack参数:给notebook.pack()添加fill='both',确保Notebook铺满主窗口。
  3. 启用第二个Treeview布局:取消tree2.pack(fill='both', expand=True)的注释,让第二个Treeview填满对应标签页。

修改后的完整代码

import tkinter as tk
from tkinter import ttk
import csv

# root window
root = tk.Tk()
root.geometry('1600x900')

# create a notebook
notebook = ttk.Notebook(root)
# 添加fill='both'让Notebook铺满主窗口
notebook.pack(fill='both', expand=True)

# 移除固定的width和height参数
EntriesFrame = ttk.Frame(notebook)
RaceFrame = ttk.Frame(notebook)

# add frames to notebook as tabs
notebook.add(EntriesFrame, text='Entries')
notebook.add(RaceFrame, text='Race')

# Set up a treeview in first tab (EntriesFrame)
ColNames = ['SailNo', 'Boat', 'HelmName', 'CrewName', 'Class', 'Fleet', 'Yardstick']
tree = ttk.Treeview(EntriesFrame, columns=ColNames, show='headings')
for ColName in ColNames:
    tree.heading(ColName, text=ColName)
tree.pack(fill='both', expand=True)

# a Treeview for the entries on the next tab.
tree2 = ttk.Treeview(RaceFrame, columns=ColNames, show='headings')
for ColName in ColNames:
    tree2.heading(ColName, text=ColName)
# 启用第二个Treeview的布局
tree2.pack(fill='both', expand=True)

root.mainloop()

效果说明

修改后,Notebook会自动铺满主窗口,两个标签页的Treeview也会各自填满对应的标签页框架,窗口缩放时所有组件都会自适应调整尺寸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 11:00:57