本文介绍了Python Tkinter用StringVar调用字典吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python中的tkinter,但我有一个似乎无法修复的烦人的错误,尽管答案可能很明显.

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.

我正在尝试用字符串调用字典,但是由于某种原因,我得到了错误:类型错误:不可哈希类型:StringVar.这是该问题的代码片段:

I am trying to call a dictionary with a string, but for some reason I get the error:Type Error: unhashable type: 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()

有关其他信息,如果我删除了与tkinter相关的代码(例如import,gpa = Tk(),StringVar,.set,mainloop()),则可以使用,所以我认为这是与tkinter相关的问题.

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.

推荐答案

就像您必须调用StringVar对象的set方法一样,您还需要调用get来检索str数据. /p>

Just as you had to call set method of StringVar object, you also need to call get to retrieve the str data.

print weightsy[acadw.get()]

字典不知道将您的对象转换为字符串,因此它尝试获取与acadw关联的值.您会得到一个TypeError而不是KeyError,因为StringVar对象碰巧是不可散列的.

The dictionary doesn't know to convert your object into a string so it attempts to get the value associated with acadw. You get a TypeError rather than a KeyError since StringVar objects happen to be unhashable.

这篇关于Python Tkinter用StringVar调用字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 17:46