2016-03-05 51 views
1

我现在被卡住了,真的可以使用一些帮助,我已经耗尽了Google可以为我找到的所有资源,而且我仍然无法弄清楚如何执行我正在尝试的操作。 (如果它甚至可能)在Python中将字典值导入到OptionMenu中

在我的python程序中,我使用Python 3.5.1中的Tkinter来制作一个小小的计算器applet。对于有问题的计算器,我创建了一个CSV文件并使用csv.DictReader导入它。

import csv 
exptable = csv.DictReader(open('C:/Users/SampleInfo.csv')) 

result = {} 
for column in exptable: 
    key = column.pop('Current Level') 
    if key in result: 
     pass 
    result[key] = column 

现在我根本弄不清楚的部分是如何使用这个导入的字典中包含的信息。下面是我想那么远,

DropDownLevelVar = StringVar() 
DropDownLevel = ttk.OptionMenu(root, {column}) 
DropDownLevel.grid(column=3, row=1) 

这是留给我......

Error on line 49, in module DropDownLevel = ttk.OptionMenu(root, {column}) 

TypeError: unhashable type: 'dict' 

的CSV词典我想使用包含数据的2列,“现时水平和总EXP“请参阅This for what the Data looks like.

我想要的是OptionMenu下拉列表中填充字典中当前级别下列出的值。

我的目标是创建一个超级简单的计算器,该计算器可以计算出我需要杀死多少个怪物以达到我想要的级别。 (如果当前等级= 55,那么100杀死在500xp ea直到56)。我导入了字典,以便我可以反复参考值,如果我需要。

我真的很新编程,所以我很抱歉,如果我看起来像一个完整的白痴!

回答

1

为什么不使用this method来填充字典?

总之,要正确填充result字典:

import csv 
exptable = csv.DictReader(open('C:/Users/SampleInfo.csv')) 

result = {} 
for column in exptable: # should actually be called `row` 
    key = column['Current Level'] 
    if key not in result: 
     result[key] = column['Total EXP'] 

forif块可以更好的写法如下:

for column in exptable: # should actually be called `row` 
    if column['Current Level'] not in result: 
     result[column['Current Level']] = column['Total EXP'] 

如果ttk.OptionMenu想要一个字典,那么该行DropDownLevel = ttk.OptionMenu(root, {column})或许应该成为:

DropDownLevel = ttk.OptionMenu(root, result) 

编辑:而pythonic方式做到这一点,按照上面链接的方法:

import csv 

result = {} 
with open('C:/Users/SampleInfo.csv') as csvfile: 
    reader = csv.DictReader(csvfile) 
    for row in reader: 
     if row['Current Level'] not in result: # is this check necessary? 
      result[row['Current Level']] = row['Total EXP'] 
+0

Dang完美!十分感谢你的帮助!!我以这种方式进行导入只是因为我是新手,你的方法看起来更干净! –

+0

@MaxwellDeFilippis如果您发现有用的答案,请考虑投票并接受适当的答案。请参阅“[当某人回答我的问题时该怎么办?](http://stackoverflow.com/help/someone-answers)” – aneroid