You need to enable JavaScript to run this app. Tkinter Treeview组件三击事件仅首个tag_configure执行问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter Treeview组件三击事件仅首个tag_configure执行问题求助

问题根因

ttk.Treeview 的tag样式优先级由绑定到条目时的先后顺序决定,后绑定的tag样式会覆盖先绑定tag的同属性配置。你插入条目时给每个条目绑定的tag顺序为('trClicked'+str(count), 'normal'+str(count)),normal开头的tag优先级更高,所以修改trClicked系列tag的样式会被normal系列的样式覆盖,才会出现只有一个tag_configure生效的现象。

另外给每个条目单独生成两个专属tag的写法完全没有必要,尤其你有6万+条目的场景,会额外占用大量内存,也会拖慢运行效率。

修复方案

全局仅定义两个通用tag即可,提前配置好样式,三击时只需要切换对应条目的tag就能实现效果,性能更高逻辑也更清晰。
修改后的可运行代码如下:

from tkinter import *
from tkinter import ttk

def onTripleClick(event):
    global prev_tr_clicked
    current_iid = tree.focus()
    # 先清除之前高亮的条目样式
    if prev_tr_clicked is not None:
        tree.item(prev_tr_clicked, tags=('normal',))
    # 给当前点击条目设置高亮
    tree.item(current_iid, tags=('trClicked',))
    # 记录当前高亮条目iid
    prev_tr_clicked = current_iid


# Create main root object of TK class
root = Tk()
root.title('MyTreeview')
root.geometry("700x500")

# create frame to house treeview AND scrollbar
frame = Frame(root)
frame.pack(pady=5)

tree = ttk.Treeview(frame, height=20, selectmode="browse")
tree.pack(side=LEFT)
tree['columns'] = ("Column1", "Column2", "Column3")

# 提前全局配置两个tag的样式
tree.tag_configure('normal', background='white', foreground='black', font=('Courier' ,8, 'normal', 'roman'))
tree.tag_configure('trClicked', background='light green', foreground='black', font=( 'Helvetica' ,8, 'bold', 'italic'))

#Format Columns
tree.column("#0", width=10, minwidth=10) # this is where the plus icon will live
tree.column("Column1", anchor=W, width=150)
tree.column("Column2", anchor=W, width=300)
tree.column("Column3", anchor=W, width=120)

# Create headings
tree.heading("#0", text="", anchor=W)
tree.heading("Column1", text="Column1", anchor=W)
tree.heading("Column2", text="Column2", anchor=W)
tree.heading("Column3", text="Column3", anchor=W)

# 存储上次高亮的条目iid
prev_tr_clicked = None

rows= [
    ['TopMostParent1', '2ndParent-ColE', 'ColF-3rdParent'],
    ['TopMostParent2', '5thParent-ColE', 'ColF-1stParent'],
    ['TopMostParent3', '4thParent-ColE', 'ColF-2ndParent'],
    ['TopMostParent4', '2ndParent-ColE', 'ColF-3rdParent'],
    ['TopMostParent4', '4thParent-ColE', 'ColF-1stParent'],
    ['TopMostParent6', '3rdParent-ColE', 'ColF-2ndParent'],
    ['TopMostParent5', '3rdParent-ColE', 'ColF-1stParent'],
    ['TopMostParent4', '3rdParent-ColE', 'ColF-3rdParent'],
    ['TopMostParent2', '3rdParent-ColE', 'ColF-3rdParent']
]
count=0
for row in rows:
    # 插入条目时默认绑定normal标签即可
    tree.insert(parent='', index='end', iid=count, text='', tags=('normal',), values=(row[0], row[1], row[2]))
    count+=1

tree.bind("<Triple-1>", onTripleClick)

root.mainloop()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 19:36:00