问题描述
我希望它能够打开一个对话窗口并选择我的文件,
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设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)