如何移除Tkinter Treeview组件的边框?
移除Tkinter Treeview的边框
我想用Tkinter的Treeview制作一个带两行表头的表格,顶部表头跨下方两列,目前已经实现了布局效果,但顶部Treeview的底部边框无法移除,尝试了配置样式但没有效果。
我的代码如下:
# 顶部表头Treeview(两列) self.tree_heading = ttk.Treeview(self.root, columns=("ColumnA", "ColumnB"), show="headings", height=0) self.tree_heading.column("ColumnA", width=200) self.tree_heading.column("ColumnB", width=200) self.tree_heading.heading("ColumnA", text="Column A") self.tree_heading.heading("ColumnB", text="Column B") self.tree_heading.grid(row=0, column=0, pady=(10, 0)) # 下方内容Treeview(四列) self.tree = ttk.Treeview(self.root, columns=("Column1", "Column2", "Column3", "Column4"), show="headings") self.tree.column("Column1", anchor="center", width=100) self.tree.column("Column2", anchor="center", width=100) self.tree.column("Column3", anchor="center", width=100) self.tree.column("Column4", anchor="center", width=100) self.tree.heading("Column1", text="Column 1", anchor="center") self.tree.heading("Column2", text="Column 2", anchor="center") self.tree.heading("Column3", text="Column 3", anchor="center") self.tree.heading("Column4", text="Column 4", anchor="center")
尝试过以下样式配置,但没有效果:
self.style = ttk.Style() self.style.configure("Custom.Treeview", borderwidth=0, relief="flat")
解决方法
方法1:正确应用自定义样式
你之前的问题是没有将自定义样式绑定到顶部的Treeview组件,修改代码如下:
self.style = ttk.Style() # 配置自定义样式 self.style.configure("Custom.Treeview", borderwidth=0, relief="flat") # 创建顶部Treeview时指定style参数 self.tree_heading = ttk.Treeview(self.root, style="Custom.Treeview", columns=("ColumnA", "ColumnB"), show="headings", height=0) # 后续的列配置、表头设置和布局保持不变 self.tree_heading.column("ColumnA", width=200) self.tree_heading.column("ColumnB", width=200) self.tree_heading.heading("ColumnA", text="Column A") self.tree_heading.heading("ColumnB", text="Column B") self.tree_heading.grid(row=0, column=0, pady=(10, 0))
方法2:修改样式布局(彻底移除边框)
如果方法1在某些系统主题下仍有残留边框,可以通过重新定义Treeview的布局,去掉边框元素:
self.style = ttk.Style() # 重新布局Custom.Treeview,只保留内容区域,移除边框组件 self.style.layout("Custom.Treeview", [ ("Treeview.treearea", {"sticky": "nswe"}) ]) # 应用样式到顶部Treeview self.tree_heading = ttk.Treeview(self.root, style="Custom.Treeview", columns=("ColumnA", "ColumnB"), show="headings", height=0)
无缝衔接优化
为了让顶部表头和下方Treeview完全贴合,可调整grid的sticky参数,确保组件铺满列宽:
self.tree_heading.grid(row=0, column=0, sticky="ew", pady=(10, 0)) self.tree.grid(row=1, column=0, sticky="ew")
内容的提问来源于stack exchange,提问作者Soul Serenity
相关产品推荐
相关产品推荐

