如何将对话框窗口中的选定文件添加到字典中?
问题描述
我希望它能够打开一个对话窗口并选择我的文件,
I wish it's able to open a dialog window and select my files,
a.txt
b.txt
然后将它们添加到我的字典中
then add them in my dictionary
myDict = { "a.txt" : 0,
"b.txt" : 1}
我在网站上搜索过
import Tkinter,tkFileDialog
root = Tkinter.Tk()
filez = tkFileDialog.askopenfilenames(parent=root,multiple='multiple',title='Choose a file')
这些代码用于打开对话窗口并选择我的文件.但问题是如何将选中的文件添加到字典中?
these codes work for opening a dialog window and selecting my files. But the question is how to add the selected files to the dictionary?
有了斯蒂芬的回答,问题就解决了
With Stephan's answer, the problem is solved
myDict = {}
for filename in filez:
myDict[filename] = len(myDict)
print "myDict: " + str(myDict)
现在 myDict 是
Now the myDict is
myDict = {'C:/a.txt': 0}
myDict = {'C:/a.txt': 0, 'C:/b.txt': 1}
网上搜索后,添加os.path.split
After searching online, just add os.path.split
myDict = {}
for filename in filez:
head, tail = os.path.split(str(filename))
myDict[tail] = len(myDict)
现在一切正常
myDict = {'a.txt': 0, 'b.txt': 1}
我得到了没有路径的 myDict,问题解决了!谢谢!
I got the myDict without path, problem solved! Thanks!
解决方案
myDict = {}
myDict[filenameFromDialog] = len(myDict)
这是添加到字典的语法.
That is the syntax for adding to a dictionary.
如果您有一组文件要添加到字典中,您可以遍历列表并一次添加一个:
If you have an array of files you want to add to the dictionary, you could loop over the list and add them one at a time:
myDict = {}
for filename in filez:
myDict[filename] = len(myDict)
相关文章