You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python Tkinter Treeview控件中实现Ctrl+A一键全选所有行?

Add Ctrl+A Select-All to Tkinter Treeview

Got it, let's add that handy Ctrl+A select-all functionality to your Treeview. Here's a simple, effective way to modify your code:

First, we'll create a function that handles selecting all rows, then bind the Ctrl+A shortcut to your Treeview widget.

Step 1: Define the Select-All Function

This function will clear any existing selection, grab all rows in the Treeview, and select them all:

def select_all(event):
    # Clear current selection to start fresh
    event.widget.selection_clear()
    # Get all unique IDs for every row in the Treeview
    all_rows = event.widget.get_children()
    # Add each row to the selection
    for row_id in all_rows:
        event.widget.selection_add(row_id)

Step 2: Bind the Shortcut & Full Modified Code

We'll bind both lowercase and uppercase Ctrl+A to cover cases where Caps Lock might be on. Here's the complete working code:

import tkinter as tk
from tkinter import ttk

def select_all(event):
    # Clear existing selection
    event.widget.selection_clear()
    # Fetch all row IDs
    all_rows = event.widget.get_children()
    # Select every row
    for row_id in all_rows:
        event.widget.selection_add(row_id)

root = tk.Tk()
cols = ('name','age')
e = ttk.Treeview(root,columns=cols)
for col in cols:
    e.heading(col, text=col)
    e.column(col,minwidth=0,width=170)

# Bind Ctrl+A (both cases) to the select-all function
e.bind('<Control-a>', select_all)
e.bind('<Control-A>', select_all)

e.pack()
e.insert("","end",values=("ss",66))
e.insert("","end",values=("yy",11))
root.mainloop()

How It Works:

  • selection_clear() ensures we don't add to an existing selection (perfect for the standard Ctrl+A behavior that replaces current selection).
  • get_children() retrieves all top-level row IDs in the Treeview (works for flat structures like yours; nested rows would need recursion, but that's not needed here).
  • Binding both <Control-a> and <Control-A> makes the shortcut work regardless of Caps Lock state.

Now pressing Ctrl+A will instantly select all rows in your Treeview!

内容的提问来源于stack exchange,提问作者Jung-suk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 17:02:39