
本文将介绍如何在Tkinter中使用自定义类创建带滚动条的TreeView控件。摘要如下:本文介绍了如何在使用Tkinter自定义类创建TreeView控件时正确集成滚动条。关键在于确保将父控件传递给ttk.Treeview的初始化函数,并正确配置滚动条与TreeView的关联。同时,通过设置fill和expand参数,可以使TreeView控件更好地适应窗口大小变化。
在使用Tkinter创建GUI应用程序时,TreeView控件是一个常用的组件,用于显示分层数据。当数据量较大时,我们需要添加滚动条以便用户浏览所有内容。如果使用自定义类来创建TreeView,可能会遇到滚动条无法正确显示的问题。本文将详细介绍如何解决这个问题,并提供示例代码。
核心问题:父控件传递
在自定义的TreeView类中,继承ttk.Treeview时,务必将父控件传递给super().__init__()。这是因为ttk.Treeview需要知道它属于哪个父控件,才能正确地进行布局和滚动条的关联。如果忘记传递父控件,ttk.Treeview会被创建为根窗口的子控件,导致滚动条显示位置错误。
示例代码:
以下是一个示例代码,展示了如何正确地使用自定义类创建带滚动条的TreeView:
from tkinter import *
from tkinter import ttk
class myTree(ttk.Treeview):
def __init__(self, parent, width, *args):
super().__init__(parent) # 关键:传递父控件
#parent widget, width and fields provided when object is created
self['show'] = 'headings'
#create columns
self['columns'] = args #args contains field names
for column in args:
self.column(column, anchor=CENTER, width=width)
#and headings
for column in args:
self.heading(column, text=column, anchor=CENTER)
main = Tk()
frame1 = Frame(main)
frame1.pack()
test = myTree(frame1,100,'A', 'B', 'C', 'D', 'E')
#add vertical scroll bar
scrollbarV = ttk.Scrollbar(frame1,orient=VERTICAL, command=test.yview)
scrollbarV.pack(side='right', fill='y')
test.config(yscrollcommand=scrollbarV.set)
#add horizontal scroll bar
scrollbarH = ttk.Scrollbar(frame1,orient=HORIZONTAL, command=test.xview)
scrollbarH.pack(side='bottom', fill='x')
test.config(xscrollcommand=scrollbarH.set)
test.pack(fill="both", expand=1) # 推荐:设置fill和expand
main.mainloop()代码解释:
- super().__init__(parent): 在myTree类的__init__方法中,调用super().__init__(parent),确保将父控件传递给ttk.Treeview的初始化函数。
- test.config(yscrollcommand=scrollbarV.set) 和 test.config(xscrollcommand=scrollbarH.set): 将TreeView的yscrollcommand和xscrollcommand属性设置为滚动条的set方法,实现滚动条与TreeView的联动。注意这里是yscrollcommand和xscrollcommand,而不是yscroll和xscroll。
- test.pack(fill="both", expand=1): 设置TreeView的pack方法的fill参数为"both",使TreeView在水平和垂直方向上填充可用空间。设置expand参数为1,使TreeView在窗口大小改变时自动扩展。这两个参数的设置可以使TreeView更好地适应窗口大小的变化。
注意事项:
- 确保滚动条和TreeView都添加到同一个父控件中。
- 正确设置滚动条的command属性和TreeView的yscrollcommand和xscrollcommand属性,实现滚动条与TreeView的联动。
- 使用fill和expand参数,使TreeView更好地适应窗口大小变化。
总结:
通过正确地传递父控件,配置滚动条的command属性和TreeView的yscrollcommand和xscrollcommand属性,以及使用fill和expand参数,我们可以轻松地在使用Tkinter自定义类创建TreeView控件时集成滚动条,并获得良好的用户体验。










