如何让ttk.Treeview控件不记忆最后点击或选中的项目?
ttk.Treeview清除最后点击项目记忆的方法
问题现象
选中ttk.Treeview中的项目后,即使通过.selection_remove()取消选中,控件仍会记住最后被鼠标点击的项目。后续使用Shift键批量选择时,仍会以该项目为起点/终点,而非新点击的项目。
演示代码
import tkinter as tk from tkinter import ttk class App: def __init__(self): self.root = tk.Tk() self.tree = ttk.Treeview(self.root) self.tree.pack(side="top", fill="both") self.tree.bind("<Leave>", self.remove_selection_appearance) for i in range(20): self.tree.insert("", "end", text="Item %s" % i) self.root.mainloop() def remove_selection_appearance(self, event): selected_items = event.widget.selection() print(f"{selected_items=}") event.widget.selection_remove(selected_items) # event.widget.selection_toggle(selected_items) # event.widget.selection_set("") if __name__ == "__main__": app = App()
行为示例
- 鼠标进入再离开控件,打印
selected_items=() - 点击Item 3后移出鼠标,打印
selected_items=('I004',) - 按住Shift键点击Item 7后移出鼠标,打印
selected_items=('I004', 'I005', 'I006', 'I007', 'I008') - 按住Shift键点击Item 0后移出鼠标,打印
selected_items=('I001', 'I002', 'I003', 'I004')
原因与解决方案
这是ttk.Treeview的内置行为:控件会维护一个独立于选中状态的锚点项目(anchor item),用于Shift批量选择的参考基准,锚点不会随选中状态的清除而自动重置。
要彻底清除这个记忆的锚点,需在取消选中的同时,额外执行两个操作:
- 重置选择集合为空
- 清除控件的焦点(focus)
修改后的remove_selection_appearance方法如下:
def remove_selection_appearance(self, event): selected_items = event.widget.selection() print(f"{selected_items=}") # 清空所有选中项 event.widget.selection_set(()) # 清除焦点,重置锚点 event.widget.focus("")
修改后,Treeview将不再保留之前的点击记忆,后续Shift选择会以新点击的项目作为基准。
内容的提问来源于stack exchange,提问作者Sun Bear
相关产品推荐
相关产品推荐

