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

Tkinter中ttk.Treeview类表格组件水平滚动条无法正常使用问题求助

解决方案

问题根因

  • 滚动条变量被覆盖:代码中先后创建的垂直、水平滚动条都赋值给了同一个game_scroll变量,导致先创建的垂直滚动条丢失引用,滚动条和Treeview的绑定逻辑完全混乱
  • 滚动触发条件不满足:列默认开启自动拉伸适配,内容会被挤压适配Treeview显示宽度,不会触发水平滚动

修复后可运行代码

from tkinter import *
from tkinter import ttk

ws = Tk()
ws.title('PythonGuides')
ws.geometry('500x500')
ws['bg'] = 'Black'

game_frame = Frame(ws)
game_frame.pack(fill=BOTH, expand=True)

# 垂直、水平滚动条使用独立变量
game_scroll_y = Scrollbar(game_frame, orient='vertical')
game_scroll_y.pack(side=RIGHT, fill=Y)

game_scroll_x = Scrollbar(game_frame, orient='horizontal')
game_scroll_x.pack(side=BOTTOM, fill=X)

# 分别绑定对应滚动条的set方法
my_game = ttk.Treeview(game_frame, yscrollcommand=game_scroll_y.set, xscrollcommand=game_scroll_x.set)
my_game.pack(fill=BOTH, expand=True)

# 分别给两个滚动条绑定视图控制命令
game_scroll_y.config(command=my_game.yview)
game_scroll_x.config(command=my_game.xview)

my_game['columns'] = ('_id', '_name')

my_game.column("#0", width=0, stretch=NO)
my_game.column("_id", anchor=CENTER, width=80, stretch=NO)
# 关闭列自动拉伸,内容超宽时会触发水平滚动
my_game.column("_name", anchor=CENTER, width=180, stretch=NO)

my_game.heading("#0", text="", anchor=CENTER)
my_game.heading("_id", text="Id", anchor=CENTER)
my_game.heading("_name", text="Step", anchor=CENTER)

# 添加测试数据
for i in range(40):
    my_game.insert(parent='', index='end', iid=i, text='', values=(str(i + 1), 'Going to the step ' + str(i + 1)))

ws.mainloop()

核心修改说明

  • 拆分滚动条变量:避免变量覆盖导致的引用丢失,确保两个滚动条都可以正常绑定逻辑
  • 修正绑定关系:垂直滚动条绑定y轴视图控制,水平滚动条绑定x轴视图控制,对应关系不会出错
  • 关闭列自动拉伸:设置stretch=NO避免内容被挤压适配窗口,当内容总宽度超过Treeview显示宽度时自动触发水平滚动
  • 布局适配:给容器添加fill=BOTH, expand=True让表格区域撑满窗口,优化使用体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:54:03