You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Tkinter Treeview选中文件无法获取正确完整绝对路径问题咨询

错误原因
  • 你在select方法中仅读取了当前选中节点的text属性(仅为单个文件名/目录名),直接调用os.path.abspath()时,该方法会默认将文件名和Python脚本当前运行的工作目录拼接,不会主动拼接该节点在目录树中对应的父级路径,因此得到的路径缺少层级。
  • 你在构建目录树生成节点时,已经计算过每个节点对应的绝对路径,但没有将该路径存储到节点属性中,双击时无法直接获取。
修复方法
  1. 插入节点时将对应绝对路径存入节点的values属性预留读取
    修改process_directory方法:
def process_directory(self, parent, path):
    for p in os.listdir(path):
        abspath = os.path.join(path, p)
        isdir = os.path.isdir(abspath)
        # 插入节点时传入绝对路径存到values中
        oid = self.tree.insert(parent, 'end', text=p, open=False, values=(abspath,))
        if isdir:
            self.process_directory(oid, abspath)

同时给根节点也加上路径存储,避免双击根目录报错,找到__init__中插入根节点的行,修改为:

root_node = self.tree.insert('', 'end', text=abspath, open=True, values=(abspath,))
  1. 修改select方法直接读取预存的绝对路径
def select(self):
    for i in self.tree.selection():
        # 读取节点中提前存好的绝对路径
        full_path = self.tree.item(i)['values'][0]
        print(full_path)
        self.openfolderfile(full_path)

额外优化建议:可以将双击事件绑定改为<Double-Button-1>,仅响应鼠标左键双击,避免其他按键触发误操作。


内容的提问来源于stack exchange,提问作者mrpy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 09:54:04