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

Viewed 961

1-How to select all treeview, (ctrl+a) and copy it with(ctrl-c), I found how to select multiple row.

2-is it possible to paste the sélection as an array, not as a texte, for example when I paste the sélection in Excel it will be in several columns.

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 Answers
  1. Bind Ctrl+C to a copy() function that retrieves the values of the selected rows and put it in the clipboard. For that you can use:
  • tree.selection() to get the selected rows iids
  • tree.item(<iid>, 'text') to get the content of the first column
  • tree.item(<iid>, 'values') to get the content of the other columns
  • root.clipboard_clear() to clear the clipboard
  • root.clipboard_append(<string>) to append text to the clipboard
  1. LibreOffice (so I guess Excel too but I haven't tried) suggests to paste in different columns content separated by tabs (I think it is possible to use other kinds of separators). So the idea is to separate the values of one row by tabs and the rows by newlines.

UPDATE: to copy the headers as well, you can retrieve the header properties with tree.heading("#<column number>", <option>), so

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

gives you the list of all column headers.

The full code for the copy() function is:

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)
Related