如何设置Tkinter中Treeview关联滚动条的高度?
解决ttk.Treeview滚动条高度过短的问题
问题描述
我有一个关联了滚动条的ttk.Treeview表格,滚动功能正常,但滚动条高度过短,请问该如何设置它的高度?
我的代码实现
class table(ttk.Treeview): def __init__(self,frame,scroll_width,list_height,side,x_crol,y_crol,lable_place_x, lable_place_y): self.side = side scroll = Scrollbar(frame, orient="vertical", width=scroll_width) scroll.pack(side=side) scroll.place(x=x_crol, y=y_crol) ttk.Treeview.__init__(self,frame, yscrollcommand=scroll.set, height=list_height) self.pack(side=LEFT, padx=lable_place_x + 30, pady=lable_place_y + 50) scroll.config(command=self.yview) scroll_width=20 tab_side=LEFT x=650 y= 160 frame=hospitalFrame list_height=20 c = 80 lable_place_x = 80 lable_place_y=70 hospital_tabel=table(frame,scroll_width,list_height,tab_side,x,y,lable_place_x, lable_place_y) hospitalFrame.pack(fill='both',expand=1)
效果截图

问题原因
代码里对滚动条同时使用了pack()和place()两种布局方法,导致布局逻辑冲突;且place()只设置了坐标,未指定高度,滚动条只能显示默认最小高度。另外原代码中_init__写法错误,必须是__init__(前后各两个下划线),否则类初始化方法无法生效。
解决方法
方法1:统一使用pack布局(推荐)
Treeview用pack()布局时,滚动条也用pack()可自动对齐高度,无需手动设置坐标,窗口大小变化时还能自动调整:
class table(ttk.Treeview): def __init__(self,frame,scroll_width,list_height,side,lable_place_x,lable_place_y): self.side = side # 初始化滚动条并绑定Treeview的yview方法 scroll = ttk.Scrollbar(frame, orient="vertical", width=scroll_width, command=self.yview) # 初始化Treeview并绑定滚动条的set方法 ttk.Treeview.__init__(self,frame, yscrollcommand=scroll.set, height=list_height) # 用pack布局实现并排,fill=Y让滚动条匹配Treeview高度 self.pack(side=LEFT, padx=lable_place_x + 30, pady=lable_place_y + 50, fill=Y) scroll.pack(side=side, fill=Y) # 实例化时无需传入x_crol和y_crol参数 scroll_width=20 tab_side=LEFT frame=hospitalFrame list_height=20 lable_place_x = 80 lable_place_y=70 hospital_tabel=table(frame,scroll_width,list_height,tab_side,lable_place_x,lable_place_y) hospitalFrame.pack(fill='both',expand=1)
方法2:使用place布局(需手动指定高度)
如果必须用place()固定滚动条位置,需要手动设置height参数,比如匹配Treeview的总高度:
class table(ttk.Treeview): def __init__(self,frame,scroll_width,list_height,side,x_crol,y_crol,lable_place_x,lable_place_y): self.side = side scroll = ttk.Scrollbar(frame, orient="vertical", width=scroll_width) # 手动计算滚动条高度,假设每行高度为20,根据list_height计算总高度 tree_total_height = list_height * 20 scroll.place(x=x_crol, y=y_crol, height=tree_total_height) ttk.Treeview.__init__(self,frame, yscrollcommand=scroll.set, height=list_height) self.pack(side=LEFT, padx=lable_place_x + 30, pady=lable_place_y + 50) scroll.config(command=self.yview) # 保持原实例化参数不变 scroll_width=20 tab_side=LEFT x=650 y= 160 frame=hospitalFrame list_height=20 c = 80 lable_place_x = 80 lable_place_y=70 hospital_tabel=table(frame,scroll_width,list_height,tab_side,x,y,lable_place_x,lable_place_y) hospitalFrame.pack(fill='both',expand=1)
额外提示
- 建议用
ttk.Scrollbar替代Scrollbar,和ttk.Treeview保持组件风格统一,样式更协调 - 避免同时混用多种布局管理器(pack/place/grid),极易引发布局混乱
内容的提问来源于stack exchange,提问作者עינב דחליקה
相关产品推荐
相关产品推荐

