Python 在 tkinter 中打开多个文件名并将文件名添加到列表中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/16790328/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
open multiple filenames in tkinter and add the filesnames to a list
提问by faraz
what I want to do is to select multiple files using the tkinter filedialog and then add those items to a list. After that I want to use the list to process each file one by one.
我想要做的是使用 tkinter 文件对话框选择多个文件,然后将这些项目添加到列表中。之后我想使用列表来一个一个地处理每个文件。
#replace.py
import string
def main():
        #import tkFileDialog
        #import re
        #ff = tkFileDialog.askopenfilenames()
        #filez = re.findall('{(.*?)}', ff)
        import Tkinter,tkFileDialog
        root = Tkinter.Tk()
        filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
Now, I am able to select multiple files, but I dont know how to add those filenames to the list. any ideas?
现在,我可以选择多个文件,但我不知道如何将这些文件名添加到列表中。有任何想法吗?
采纳答案by A. Rodas
askopenfilenamesreturns a string instead of a list, that problem is still open in the issue tracker, and the best solution so far is to use splitlist:
askopenfilenames返回一个字符串而不是一个列表,该问题在问题跟踪器中仍然存在,目前最好的解决方案是使用splitlist:
import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
print root.tk.splitlist(filez)
回答by Belial
askopenfilenames
returns a tuple of strings, not a string. Simply store the the output of askopenfilenamesinto filez (as you've done) and pass it to the python's listmethod to get a list.
返回一个字符串元组,而不是一个字符串。只需将askopenfilenames的输出存储到 filez 中(如您所做的那样)并将其传递给 python 的list方法以获取列表。
filez = tkFileDialog.askopenfilenames(parent=root,title='Choose a file')
lst = list(filez)
>>> type(lst)
<type 'list'>
回答by mvx
Putting together parts from above solution along with few lines to error proof the code for tkinter file selection dialog box (as I also described here).
将上述解决方案中的部分与几行放在一起,以防止 tkinter 文件选择对话框的代码出错(正如我在此处所述)。
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
root.call('wm', 'attributes', '.', '-topmost', True)
files = filedialog.askopenfilename(multiple=True) 
%gui tk
var = root.tk.splitlist(files)
filePaths = []
for f in var:
    filePaths.append(f)
filePaths
Returns a list of the paths of the files. Can be strippedto show only the actual file name for further use by using the following code:
返回文件路径的列表。可以stripped使用以下代码仅显示实际文件名以供进一步使用:
fileNames = []
for path in filePaths:
    name = path[46:].strip() 
    name2 = name[:-5].strip() 
    fileNames.append(name2)
fileNames
where the integers (46) and (-5) can be altered depending on the file path.
其中整数 (46) 和 (-5) 可以根据文件路径进行更改。

