有什么方法可以获取在 python Tkinter Treeview 中选择的文件的完整路径

Is there any way to get the full path of a file selected in python Tkinter Treeview

我看过这个帖子,但是在尝试这个之后我只得到了前一个父节点的路径。如果目录树有很多分支怎么办。我需要选择的完整路径。

例如

在这里,当我单击 beaglebone 时,我得到了路径 D:\eclipse\beaglebone。但是当 .metadata 被点击时,我得到了路径 beaglebone\.metadata。但我的期望是得到 D:\eclipse\beaglebone\.metadata.

OnDoubleClick() 我需要获取完整路径。有人知道吗?

我的代码是,

class DirectoryTree(object):
    def __init__(self, frame, path):
        self.nodes = dict()
        self.tree = ttk.Treeview(frame,  height="18")
        self.tree.grid()

        self.tree.heading('#0', text='Select file', anchor='nw')
        self.tree.column('#0', width=225, minwidth=400)

        # Scrollbar
        ysb = ttk.Scrollbar(frame, orient='vertical', command=self.tree.yview)
        ysb.grid(row = 0, column = 1, sticky='ns')
        xsb = ttk.Scrollbar(frame, orient='horizontal', command=self.tree.xview)
        xsb.grid(row = 1, column = 0, sticky='we')
        self.tree.configure(xscroll=xsb.set, yscroll=ysb.set)

        abspath = os.path.abspath(path)
        self.insert_node('', abspath, abspath)
        self.tree.bind('<<TreeviewOpen>>', self.open_node)
        self.tree.bind("<Double-1>", self.OnDoubleClick)

    def insert_node(self, parent, text, abspath):
        node = self.tree.insert(parent, 'end', text=text, open=False)
        if os.path.isdir(abspath):
            self.nodes[node] = abspath
            self.tree.insert(node, 'end')

    def open_node(self, event):
        node = self.tree.focus()
        abspath = self.nodes.pop(node, None)
        if abspath:
            self.tree.delete(self.tree.get_children(node))
            for p in os.listdir(abspath):
                self.insert_node(node, p, os.path.join(abspath, p))

    def delete_nodes(self):
        x = self.tree.get_children()
        for item in x:
            self.tree.delete(item)

    def OnDoubleClick(self, event):
        item = self.tree.selection()[0]
        parent_iid = self.tree.parent(item)
        node = self.tree.item(parent_iid)['text']
        i = self.tree.item(item,"text")
        path=os.path.join(node, i)
        
        if (os.path.isfile(path)):
            print("file:", path)
            submit_file(i)
        else:
            print("dir:", path)    

您需要向后移动树直到到达根:

    def OnDoubleClick(self, event):
        item = self.tree.selection()[0]
        parent_iid = self.tree.parent(item)
        node = []
        # go backward until reaching root
        while parent_iid != '':
            node.insert(0, self.tree.item(parent_iid)['text'])
            parent_iid = self.tree.parent(parent_iid)
        i = self.tree.item(item, "text")
        path = os.path.join(*node, i)
        ...