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

如何使用Tkinter的grid布局管理器将滚动条置于Treeview左侧?

解决Treeview左侧放置滚动条(grid布局)的问题

当然可以将滚动条放在Treeview左侧,你之前的问题是列的布局顺序和权重配置不对,调整以下几点就能实现:

  1. 交换滚动条和Treeview的grid列位置:把滚动条放在column=0,Treeview放在column=1
  2. 给Treeview所在的列(column=1)设置权重,让它占据窗口的剩余空间
  3. 滚动条的sticky属性设置为'ns'(或'nsw'),保证它垂直拉伸

修改后的完整代码如下:

import tkinter as tk
from tkinter import ttk
from pathlib import Path

root = tk.Tk()

root.grid_rowconfigure(0, weight=1)
# 调整列权重:让Treeview所在的column1占满空间
root.grid_columnconfigure(1, weight=1)

paths = Path('.').glob('**/*')

tv = ttk.Treeview(root, columns=['size','modified'], selectmode=None)

tv.heading('#0', text='Name')
tv.heading('size', text='Size', anchor='center')
tv.heading('modified', text='Modified', anchor='center')

tv.column('#0', stretch = True, anchor='w')
tv.column('size', width=100, anchor='center') 
tv.column('modified',anchor='center')

# Treeview放在column=1,占满单元格
tv.grid(row=0, column=1, sticky='nsew')

for path in paths:
    meta = path.stat()
    parent = str(path.parent)
    if parent == '.':
        parent = ''
               
    tv.insert(parent, 'end', iid=str(path), text=str(path.name), values=[meta.st_size, meta.st_mtime])

scrollbar = ttk.Scrollbar(root, orient=tk.VERTICAL, command=tv.yview)
tv.configure(yscrollcommand=scrollbar.set)
# 滚动条放在column=0,垂直拉伸
scrollbar.grid(row=0, column=0, sticky='ns')
        
root.mainloop()

关键改动说明:

  • 原来的root.grid_columnconfigure(0, weight=1)改成了root.grid_columnconfigure(1, weight=1),因为现在Treeview在column1,需要让这一列随窗口拉伸
  • 滚动条的grid参数从column=1改为column=0,放在Treeview左侧
  • 滚动条的sticky用'ns'即可实现垂直方向填充,'nsw'也能达到同样效果,区别是是否向左对齐(但滚动条本身宽度固定,视觉差异不大)

内容的提问来源于stack exchange,提问作者Paul-ET

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 15:12:43