简体   繁体   English

Python Tkinter使用StringVar调用字典?

[英]Python Tkinter call a dictionary with a StringVar?

I'm working with tkinter in python and I have an annoying bug that I can't seem to fix, although the answer is probably obvious. 我正在使用python中的tkinter,我有一个令人讨厌的bug,我似乎无法修复,尽管答案可能很明显。

I am trying to call a dictionary with a string, but for some reason I get the error: Type Error: unhashable type: StringVar. 我试图用字符串调用字典,但由于某种原因我得到错误:类型错误:不可用类型:StringVar。 Here is a snippet of code with that issue: 以下是该问题的代码片段:

from Tkinter import *
gpa = Tk()

weightsy = {'0': 2, '.1': 6, '.25':.2, '.5':.56, '.75':75, '1':12}
acadw = StringVar()
acadw.set(".1")
print (weightsy.get(acadw)) #Here is the issue; it should return the integer 6.

mainloop()

For extra info, if I remove the tkinter related code (such as the import, gpa = Tk(), StringVar, .set, mainloop()) it works, so I believe it is a tkinter related issue. 有关额外信息,如果我删除tkinter相关代码(例如import,gpa = Tk(),StringVar,.set,mainloop())它可以工作,所以我认为这是一个与tkinter相关的问题。

Just as you had to call set method of StringVar object, you also need to call get to retrieve the str data. 就像你必须调用StringVar对象的set方法一样,你还需要调用get来检索str数据。

print weightsy[acadw.get()]

The dictionary doesn't know to convert your object into a string so it attempts to get the value associated with acadw . 字典不知道将您的对象转换为字符串,因此它尝试获取与acadw关联的值。 You get a TypeError rather than a KeyError since StringVar objects happen to be unhashable. 你得到一个TypeError ,而不是一个KeyError ,因为StringVar对象恰巧是unhashable。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM