【问题标题】:Ask multiple directories dialog in Tkinter在 Tkinter 中询问多个目录对话框
【发布时间】:2015-04-09 15:42:58
【问题描述】:

我正在尝试选择多个文件夹。我需要相当于askopenfilenames() 的目录,但只有askdirectory() 存在,它只允许选择一个文件夹。

之前我发现了一个为 Matlab (uigetdir) 执行此操作的自定义脚本。 在 Python 中有什么方法可以做到这一点?

我需要一次批处理大约50个文件夹中的文件,一个一个选择它们是不现实的。

另外,我不是程序员,只是想处理我的地球物理数据,不能像我在其他地方看到的那样“自己编码”。 本来以为这样一个基本的东西会包含在基本功能中。

【问题讨论】:

  • 我对此知之甚少,但快速谷歌搜索发现this link。你做过很多(任何)研究吗?
  • @AdamSmith 这只是一个循环到askdirectory,这并不是 OP 想要的。
  • @Rinzler 在tkinter.askdirectory multiple directories 的第一个结果是一个带有适用代码的新闻组发布后,我对这个问题投了反对票,说“没有更好的方法来做到这一点,但这里有一些用于破解的问题。”反对意见是“这个问题没有显示任何研究工作。”
  • 我认为标准库中没有askdirectories这样的功能,但我认为它可以以某种方式实现。
  • @AdamSmith 这个问题值得赞成,以鼓励人们实施这样的对话,在我看来。拒绝并给出解决方法很容易。

标签: python python-3.x tkinter directory


【解决方案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

【讨论】:

    【解决方案2】:

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

    【讨论】:

    • 我收到一条错误消息:there is a mismatch between C/C++ and Windows locale。怎么回事???!!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    相关资源
    最近更新 更多