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

自定义Tkinter Treeview类中滚动条位置异常问题求助

问题原因及解决方法

你的问题出在自定义myTree类的构造函数中,调用父类ttk.Treeview的构造时没有传入parent参数。

默认情况下,如果创建Tkinter控件时不指定父组件,它会自动将主窗口(main)作为父容器。这就导致你创建的test实例实际是放在主窗口里,而滚动条是放在frame1中的。当frame1.pack()之后执行test.pack(),frame1(包含滚动条)就会显示在test的上方,看起来就是滚动条在Treeview控件之上。

修复步骤

只需要修改myTree类的__init__方法,在调用父类构造时传入parent参数:

class myTree(ttk.Treeview):
    def __init__(self, parent, width, *args):
        # 传入parent参数,指定Treeview的父容器
        super().__init__(parent)
        
        self['show'] = 'headings'
        
        self['columns'] = args 

        for column in args:
            self.column(column, anchor=CENTER, width=width)
            
        for column in args:
            self.heading(column, text=column, anchor=CENTER)

修改后的完整代码

from tkinter import *
from tkinter import ttk

class myTree(ttk.Treeview):
    def __init__(self, parent, width, *args):
        super().__init__(parent)
        
        self['show'] = 'headings'
        
        self['columns'] = args 

        for column in args:
            self.column(column, anchor=CENTER, width=width)
            
        for column in args:
            self.heading(column, text=column, anchor=CENTER)
        
main = Tk()

frame1 = Frame(main)
frame1.pack(fill=BOTH, expand=True)

test = myTree(frame1,100,'A', 'B', 'C', 'D', 'E')

# 添加垂直滚动条
scrollbarV = ttk.Scrollbar(frame1,orient=VERTICAL, command=test.yview)
scrollbarV.pack(side='right', fill='y')
test.config(yscroll=scrollbarV.set)

# 添加水平滚动条
scrollbarH = ttk.Scrollbar(frame1,orient=HORIZONTAL, command=test.xview)
scrollbarH.pack(side='bottom', fill='x')
test.config(xscroll=scrollbarH.set)

test.pack(side='left', fill=BOTH, expand=True)
main.mainloop()

另外给frame1.pack()和test.pack()加上fill=BOTH和expand=True,可以让控件更好地适应窗口大小变化。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:22:29