Kivy中filechooser.selection路径冗余问题求助
看起来你的问题出在相对路径的构建和Kivy FileChooser的路径解析逻辑上,具体来说是initDir末尾多余的斜杠,以及相对路径可能带来的歧义导致路径被重复拼接。
问题根源拆解
看你的代码里initDir的构建:
initDir = 'projects' if not fileType == 'project': initDir += '\\' + fileType initDir = initDir + '\\'
当fileType为project时,initDir变成了projects\\;当为subproject时,变成projects\\subproject\\。
Kivy的FileChooserListView在处理末尾带斜杠的相对路径时,可能会将其视为要进入的子目录名称(而非指向已存在的目标目录),再加上如果你的应用工作目录和预期不符(比如不小心切换到了C:\GUI\MY_KIVY_GUI\projects),就会触发路径的重复拼接,最终出现projects\projects\...或projects\subproject\projects\subproject\...的错误路径。
解决方案
方案1:移除initDir末尾的斜杠(快速修复)
这是最简单的修复方式,因为Kivy的FileChooser会自动处理目录路径的格式,不需要手动添加末尾斜杠:
def getPath(self, fileType): # create popup layout content = BoxLayout(orientation='vertical', spacing=5) popup_width = 500 self.popup = popup = Popup(title='Open ' + str(fileType), content=content, size_hint=(None, 0.9), width=popup_width) # create the filechooser initDir = 'projects' if not fileType == 'project': initDir += '\\' + fileType # 移除末尾的斜杠添加逻辑 textinput = FileChooserListView(path=initDir, size_hint=(1, 1), dirselect=False, filters=['*.' + fileType]) self.textinput = textinput # 后续按钮构建和弹窗逻辑保持不变...
方案2:使用绝对路径彻底避免歧义
如果你的应用工作目录可能发生变化,推荐用绝对路径初始化FileChooser,这样无论工作目录是什么,都能精准指向目标文件夹:
import os from pathlib import Path def getPath(self, fileType): # create popup layout content = BoxLayout(orientation='vertical', spacing=5) popup_width = 500 self.popup = popup = Popup(title='Open ' + str(fileType), content=content, size_hint=(None, 0.9), width=popup_width) # 获取当前脚本所在的目录(假设此脚本在MY_KIVY_GUI文件夹下) base_dir = Path(__file__).parent.resolve() # 构建绝对路径 initDir = base_dir / 'projects' if not fileType == 'project': initDir = initDir / fileType # 转换为字符串传给FileChooser textinput = FileChooserListView(path=str(initDir), size_hint=(1, 1), dirselect=False, filters=['*.' + fileType]) self.textinput = textinput # 后续按钮构建和弹窗逻辑保持不变...
验证效果
修改后,当fileType为project时,FileChooser会直接指向C:\GUI\MY_KIVY_GUI\projects,选中文件后返回的路径就是预期的C:\GUI\MY_KIVY_GUI\projects\test.project;subproject类型同理,路径不会再出现重复拼接的问题。
内容的提问来源于stack exchange,提问作者Sandro

