简体   繁体   中英

Different tkinter binding for any ttk treeview row

I'm writing a simple script that create a ttk treeview (that act as a table) and, when you double-click it, it opens a file (with the path saved in the dictionary). Double click opening is possible by this method:

t.bind("<Double-1>", lambda f=nt[x]["URIallegato"]: os.startfile(str(f)))

However, this doesn't gave me the ID of the row (stored in the #0 column). With the ID I can get the path of the file saved in a dictionary. Here is the full Treeview code:

t=Treeview(w)
t.pack(padx=10,pady=10)
for x in list(nt.keys()):
    t.insert("",x,text=nt[x]["allegati"])
    if nt[x]["allegati"]!="":
        t.bind("<Double-1>",
               lambda f=nt[x]["URIallegato"]: os.startfile(str(f)))

Thanks!

The normal way to do this is to bind a single binding on the treeview for a double click. The default binding for single-click will select the item, and in your double-click binding you can ask the treeview for the selected item.

If you associate values with the treeview item, you can fetch them so that you don't have to store them in a dictionary.

Here's an example:

import tkinter as tk
from tkinter import ttk

def on_double_click(event):
    item_id = event.widget.focus()
    item = event.widget.item(item_id)
    values = item['values']
    url = values[0]
    print("the url is:", url)

root = tk.Tk()
t=ttk.Treeview(root)
t.pack(fill="both", expand=True)

t.bind("<Double-Button-1>", on_double_click)

for x in range(10):
    url = "http://example.com/%d" % x
    text = "item %d" % x
    t.insert("", x,  text=text, values=[url])

root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM