从 treeview tkinter 复制项目 [英] Copy items from treeview tkinter

查看:161
本文介绍了从 treeview tkinter 复制项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的一个 tkinter 应用程序中有一个树视图,我想知道是否真的有可能,只需在用户右键单击时复制选定的字段.如果没有,是否有任何其他小部件允许用户复制 GUI 窗口中显示的选定字段.

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.

代码:

    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)

提前致谢:)

推荐答案

您必须创建一个弹出菜单并将其绑定到 Button-3.这是从我的一个项目中快速构建的示例

You have to create a popup menu and bind it to Button-3. Here is an example quickly built from one of my projects

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)

这篇关于从 treeview tkinter 复制项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆