在Tkinter中询问多个目录对话框

9
我正在尝试选择多个文件夹。我需要类似于askopenfilenames()的目录等效项,但是只有askdirectory()可用,它仅允许选择一个文件夹。
之前我在Matlab中找到了一个自定义脚本来完成这个任务(uigetdir)。是否有一种方法可以在Python中实现这个功能?
我需要批处理大约50个文件夹中的文件,逐个选择它们不现实。
另外,我不是程序员,只是试图处理我的地球物理数据,无法像其他地方建议的那样“自己编写代码”。本应该将这样基本的功能包含在基本函数中。

我对此并不是很了解,但是快速的谷歌搜索可以找到这个链接。你有进行过多少(任何)研究吗? - Adam Smith
@Rinzler 如果你想花时间来实现它,可以随意fork tkinter并这样做。 - Adam Smith
@AdamSmith 如果网络上没有关于这个主题有用的信息,他怎么能表现出一些努力呢? - nbro
1
@AdamSmith 这个问题值得点赞,以鼓励人们实现这样的对话,这是我谦虚的意见。说“不”并提供解决方法很容易。 - nbro
我找到了那个链接,但是它是从2011年的,我希望在过去的4年中已经被实现了,特别是现在已经是Python 3了。 - user4547612
显示剩余5条评论
2个回答

1

我曾经遇到同样的问题,于是我开发了自己的解决方案。使用这个方案,您可以一次选择一个目录,完成后再选择取消。

该函数返回您选择的目录列表。

def fun_directory_selector(request_string: str, selected_directory_list: list, search_directory):
    directory_path_string = filedialog.askdirectory(initialdir=search_directory, title=request_string)

       if len(directory_path_string) > 0:
        selected_directory_list.append(directory_path_string)
        fun_directory_selector('Select the next Directory or Cancel to end', 
                               selected_directory_list,
                               os.path.dirname(directory_path_string))

    return selected_directory_list

0

OP要求使用Tkinter提供的解决方案,但是这不可行,但是可以使用wxPython-Phoenix实现解决方案。

####### Retrieve a list of directories with wxPython-Phoenix   - tested on python3.5
### installation instruction for wxPython-Phoenix  : https://wiki.wxpython.org/How%20to%20install%20wxPython#Installing_wxPython-Phoenix_using_pip
### modified from : https://wxpython.org/Phoenix/docs/html/wx.lib.agw.multidirdialog.html
import os
import wx
import wx.lib.agw.multidirdialog as MDD

# Our normal wxApp-derived class, as usual
app = wx.App(0)
dlg = MDD.MultiDirDialog(None, title="Custom MultiDirDialog", defaultPath=os.getcwd(),  # defaultPath="C:/Users/users/Desktop/",
                         agwStyle=MDD.DD_MULTIPLE|MDD.DD_DIR_MUST_EXIST)

if dlg.ShowModal() != wx.ID_OK:
    print("You Cancelled The Dialog!")
    dlg.Destroy()


paths = dlg.GetPaths()

#Print directories' path and files 
for path in enumerate(paths):
    print(path[1])
    directory= path[1].replace('OS (C:)','C:')
    print(directory)
    for file in os.listdir(directory):
        print(file)

dlg.Destroy()
app.MainLoop()

我收到一个错误,说“C/C++和Windows区域设置不匹配”。发生了什么???!!! - Minion Jim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接