Копировать элементы из treeview tkinter - PullRequest
0 голосов
/ 09 июля 2020

У меня есть древовидное представление в одном из моих приложений tkinter, и я хотел знать, действительно ли это возможно, просто скопировать выбранное поле, щелкнув правой кнопкой мыши пользователем. Если нет, есть ли другой виджет, который позволяет пользователю скопировать выбранное поле, показанное в окне GUI.

Код:

    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='monkey123', 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)

Заранее спасибо :)

1 Ответ

2 голосов
/ 10 июля 2020

Вы должны создать всплывающее меню и привязать его к кнопке-3. Вот пример, быстро построенный из одного из моих проектов

popup1 = tk.Menu(tree, tearoff=0)
popup1.add_command(
    command=your_copy,
    label="Copy")

def your_copy():
    item = tree.selection()[0]
    log.clipboard_clear()
    log.clipboard_append(tree.item(item, option='text')

def popup_menu(event):
    tree.identify_row(event.y)
    popup1.post(event.x_root, event.y_root)
    
tree.bind('<Button-3>', popup_menu)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...