問題描述
我希望它能夠打開一個對話窗口并選擇我的文件,
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)
這篇關于如何將對話框窗口中的選定文件添加到字典中?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!