how to add the selected files from dialog window t

2020-03-30 08:43发布

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}

I searched on website

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)

Now the myDict is

myDict = {'C:/a.txt': 0}
myDict = {'C:/a.txt': 0, 'C:/b.txt': 1}

After searching online, just add os.path.split

myDict = {}
for filename in filez:
    head, tail = os.path.split(str(filename))
    myDict[tail] = len(myDict)

Now everything is right

myDict = {'a.txt': 0, 'b.txt': 1}

I got the myDict without path, problem solved! Thanks!

1条回答
The star\"
2楼-- · 2020-03-30 09:17
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)
查看更多
登录 后发表回答