Select and copy a particular cell in tkinter treeview

Viewed 1049

I have 4 columns in my tkinter treeview. The last column consists of url links in the form of text.

I would like to enable the users to click on the url cell they desire and they be able to copy it. Is this possible?

Any help will be greatly appreciated!

1 Answers

Let's suppose that tree variable has a Treeview object. First, you should bind an event handler to tree. Then, in your event handler function you can use tree.focus() to find out which tree item is focused now. Next, you need to identify which column the current cell has - tree.identify_column method can help with it. Finally, you can check whether it is the needed column. If it is so, you append the cell value to clipboard.

Here's a code example:

import tkinter as tk
from tkinter import ttk


def tree_click_handler(event):
    cur_item = tree.item(tree.focus())
    col = tree.identify_column(event.x)
    if col == '#3':
        root.clipboard_clear()
        root.clipboard_append(cur_item['values'][2])

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('<ButtonRelease-1>', tree_click_handler)

root.mainloop()
Related