![](/img/trans.png)
[英]TypeError: unhashable type: 'StringVar' closing a tkinter window
[英]How to deal with unhashable type 'StringVar' Python
我正在创建一个代码,将温度单位转换为其他温度单位,例如摄氏温度转换为华氏温度。 当我运行此代码时,出现错误,指出类型错误:不可哈希类型StringVar。 我不确定自己在做什么错,也不确定如何解决此问题,我们将不胜感激。
from tkinter import *
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
#======================================================================
notebook = ttk.Notebook(root)
frame3 = ttk.Frame(notebook)
notebook.add(frame3, text='Temperature')
notebook.pack(expand=1, fill="both")
#======================================================================
def Temperature_converter(*args):
v = float(temp_entry.get())
temp_dict = dict(Fahrenheit= (1/1.8, -32/1.8), Celsius= (1, 0), Kelvin= (1, -273.15))
x, y = temp_dict[temp_var1]
cels = temp_entry * x + y #turns input to celsius by mapping x and y to ratio and difference
x, y = temp_dict[temp_var2]
answer = (cels - y) / x # turns input in celsius to output
temp_label['text']=answer
#======================= ===============================================
temp_entry = Entry(frame3)
temp_entry.grid(row=0, column=0)
temp_label = Label(frame3, relief='groove', width=20, text='')
temp_label.grid(row=0, column=3)
options3 = ['Unit', 'Celsius', 'Fahrenheit', 'Kelvin']
temp_var1 = tk.StringVar(frame3)
temp_var1.set(options3[0])
temp_dropdown1 = tk.OptionMenu(frame3, temp_var1, options3[1], options3[2], options3[3])
temp_dropdown1.grid(row=1, column=0)
temp_var2 = tk.StringVar(frame3)
temp_var2.set(options3[0])
temp_dropdown2 = tk.OptionMenu(frame3, temp_var2, options3[1], options3[2], options3[3])
temp_dropdown2.grid(row=1, column=3)
temp_equal_button = Button(frame3, text='=', command=Temperature_converter)
temp_equal_button.grid(row=1, column=5)
#======================================================================
root.mainloop
要从StringVar
获取字符串,必须使用.get()
,然后字典没有问题可以找到此字符串
x, y = temp_dict[ temp_var1.get() ]
x, y = temp_dict[ temp_var2.get() ]
与Entry
相同,但还必须将字符串转换为float以进行计算
cels = float( temp_entry.get() ) * x + y
码:
def Temperature_converter(*args):
temp_dict = dict(Fahrenheit=(1/1.8, -32/1.8), Celsius=(1, 0), Kelvin=(1, -273.15))
x, y = temp_dict[temp_var1.get()]
cels = float(temp_entry.get()) * x + y
x, y = temp_dict[temp_var2.get()]
answer = (cels - y) / x
temp_label['text'] = answer
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.