Parsing the results of askopenfilenames()?

前端 未结 4 630
耶瑟儿~
耶瑟儿~ 2020-12-06 06:46

I\'m trying to get a list of filenames from tkinter.filedialog.askopenfilenames() in Python 3.2.

    files = askopenfilenames(initialdir=\"C:\\\\Users\\\\BVC         


        
相关标签:
4条回答
  • 2020-12-06 06:51

    I support Eldererathis's answer as the best solution I have found for Python versions 2.X (mainly 2.5 and above) versions under Linux, Mac OS X and Windows. When a tkFileDialog calls the askopenfilename(...,multiple=1) methods with argument multiple=1, I could not get it work properly under Windows (Linux and Mac OS X were fine) when a single file was selected (the file is processed as a 'str' instead of a 'tuple').

    I tried the files = re.findall('\{(.*?)\}', files suggested by Paul in the comments, but it did not change anything. I also tried files = tuple(files) and files = list(files), but it is not a viable workaround from what I have seen.

    So far, files = tkRoot.master.splitlist(files) is what is working under all environments I have tested (Win32, Win64, Linux32, Linux64, Mac OS X).

    0 讨论(0)
  • 2020-12-06 06:54

    I don't have an exact answer for you, because I'm still stuck in Python 2.x, but in my world askopenfilenames returns a tuple, so I doubt it would have changed so much going to 3.x. Maybe try casting as a list:

    filelist = list(files)
    

    Or using a list comprehension by iterating over it:

    filelist = [file for file in files]
    
    0 讨论(0)
  • 2020-12-06 06:56

    I just found this question when looking up why I was getting curly brackets instead of a proper list.

    Here's my work around:

    file_list=[]
    files = files = askopenfilenames(initialdir="C:\\Users\\BVCAP\\Videos", title="Select files")
    for file in files:
        file_list.append(file)
    

    I noticed that when I was using the askopenfilenames in my method I never looked at the object returned. I had treated it as a tuple and it worked fine. So knowing it could be iterated in a for loop, it made sense to append each item into a new blank list.

    I hope this helps anyone else who encounters this bug.

    0 讨论(0)
  • 2020-12-06 07:13

    This is actually a bug on the Windows version that has been present since around the 2.6 release of Python. You can find the issue on their tracker, and there's a workaround in the comments (I have not personally tried this workaround because I'm on Linux, which returns a proper tuple). I'm not aware of a fix since then, and the issue has not been marked as closed/resolved.

    The suggested workaround in the comment is essentially to do this:

    master = Tk()
    files = askopenfilenames(initialdir="C:\\Users\\BVCAP\\Videos", title="Select files")
    files = master.tk.splitlist(files) #Possible workaround
    self.num_files.set(len(files))
    
    0 讨论(0)
提交回复
热议问题