如何 select 所有 treeview 并用 ctrl-c 复制它

How to select all treeview and copy it with ctrl-c

1-如何 select 所有树视图,(ctrl+a) 并用 (ctrl-c) 复制它,我找到了如何 select 多行。

2-是否可以将选择粘贴为数组,而不是文本,例如,当我将选择粘贴到 Excel 时,它将分为几列。

import tkinter as tk
from tkinter import ttk

root = tk.Tk()
tree = ttk.Treeview(root)
tree.pack()

tree['columns'] = ('one', 'two', 'three')
tree.column('#0', width=170, stretch=tk.NO)
tree.column('one', width=100, stretch=tk.NO)
tree.column('two', width=100, stretch=tk.NO)
tree.column('three', width=180, stretch=tk.NO)

tree.heading('#0', text='Name', anchor=tk.W)
tree.heading('one', text='Col1', anchor=tk.W)
tree.heading('two', text='Col2', anchor=tk.W)
tree.heading('three', text='Col3', anchor=tk.W)

tree.insert('', 'end', text='The First Item Name',values=('Col1_1', 'Col2_1', 'https://test0.test'))
tree.insert('', 'end', text='The Second Item Name',values=('Col1_2', 'Col2_2', 'https://test1.test'))
tree.insert('', 'end', text='The Third Item Name',values=('Col1_3', 'Col2_3', 'https://test2.test'))

tree.bind('<Control-a>', lambda *args: tree.selection_add(tree.get_children())) #selected all row treeview

root.mainloop()
  1. Ctrl+C 绑定到 copy() 函数,该函数检索所选行的值并将其放入剪贴板。为此,您可以使用:
  • tree.selection() 获取选中的行 iids
  • tree.item(<iid>, 'text')获取第一列的内容
  • tree.item(<iid>, 'values')获取其他栏目内容
  • root.clipboard_clear()清除剪贴板
  • root.clipboard_append(<string>) 将文本附加到剪贴板
  1. LibreOffice(所以我猜 Excel 也是,但我没试过)建议在不同的列中粘贴由制表符分隔的内容(我认为可以使用其他类型的分隔符)。所以想法是用制表符分隔一行的值,用换行符分隔行。

UPDATE:要同时复制 header,您可以使用 tree.heading("#<column number>", <option>) 检索 header 属性,因此

headings = [tree.heading("#{}".format(i), "text") for i in range(len(tree.cget("columns")) + 1)]

为您提供所有列 header 的列表。

copy() 函数的完整代码是:

def copy(event):
    sel = tree.selection() # get selected items
    root.clipboard_clear()  # clear clipboard
    # copy headers
    headings = [tree.heading("#{}".format(i), "text") for i in range(len(tree.cget("columns")) + 1)]
    root.clipboard_append("\t".join(headings) + "\n")
    for item in sel:
        # retrieve the values of the row
        values = [tree.item(item, 'text')]
        values.extend(tree.item(item, 'values'))
        # append the values separated by \t to the clipboard
        root.clipboard_append("\t".join(values) + "\n")

tree.bind('<Control-c>', copy)