Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy items from treeview tkinter

I have a tree view in one of my tkinter app and i wanted to know if it really is possible to actually, just copy a selected field on right-clicking by the user. If not , is there any other widget tht allows the user to copy a selected field shown in GUI window.

Code:

    log = Toplevel(root)
    log.title('View all Visitors')
    log.focus_force()
    # setup treeview
    columns = (('ID', 80), ('S_ID', 80), ('S_NAME', 300), ('Title of the book', 500), ('Accession no. of 
                book', 80),
               ('Date Taken', 100), ('Due Date', 100), ('Date_Returned', 100), ('Status', 80))
    tree = ttk.Treeview(log, height=20, columns=[
                        x[0] for x in columns], show='headings')
    tree.grid(row=0, column=0, sticky='news')

    # setup columns attributes
    for col, width in columns:
        tree.heading(col, text=col)
        tree.column(col, width=width, anchor=tk.CENTER)

    # fetch data
    con = mysql.connect(host='localhost', user='root',
                        password='****', database='library')
    c = con.cursor()
    sql_command_1 = 'SELECT * FROM borrow;'
    c.execute(sql_command_1)

    # populate data to treeview
    for rec in c:
        tree.insert('', 'end', value=rec)

    # scrollbar
    sb = tk.Scrollbar(log, orient=tk.VERTICAL, command=tree.yview)
    sb.grid(row=0, column=1, sticky='ns')
    tree.config(yscrollcommand=sb.set)
    a = tree.item(tree.focus())['values']

    btn = tk.Button(log, text='Close', command=out,
                    width=20, bd=2, fg='red',font=font_text)
    btn.grid(row=2, column=0, columnspan=2, sticky=E+W)

Thanks in advance :)

like image 463
Delrius Euphoria Avatar asked Mar 29 '26 19:03

Delrius Euphoria


1 Answers

I had the same problem and created a function which is quite modular.

import pyperclip    

def copy_from_treeview(tree, event):
    selection = tree.selection()
    column = tree.identify_column(event.x)
    column_no = int(column.replace("#", "")) - 1
            
    copy_values = []
    for each in selection:
        try:
            value = tree.item(each)["values"][column_no]
            copy_values.append(str(value))
        except:
            pass
        
    copy_string = "\n".join(copy_values)
    pyperclip.copy(copy_string)

Simply bind the function to ctrl + c:

tree.bind("<Control-Key-c>", lambda x: copy_from_treeview(tree, x))
like image 129
TimoGH Avatar answered Mar 31 '26 08:03

TimoGH