简体   繁体   English

任何ttk树视图行的不同tkinter绑定

[英]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). 我正在编写一个简单的脚本,该脚本创建一个ttk树视图(充当表),并且双击它会打开一个文件(路径保存在字典中)。 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). 但是,这并没有给我该行的ID(存储在#0列中)。 With the ID I can get the path of the file saved in a dictionary. 使用ID,我可以获得保存在字典中的文件的路径。 Here is the full Treeview code: 这是完整的Treeview代码:

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. 如果您将值与treeview项相关联,则可以获取它们,从而不必将其存储在字典中。

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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