简体   繁体   中英

How to deal with unhashable type 'StringVar' Python

I am creating a code that converts temperature units to other temperature units for example Celsius to Fahrenheit. When I run this code I get an error stating type error: unhashable type StringVar. I'm not sure what I am doing wrong and am not sure how to resolve this problem any help would be appreciated.

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

To get string from StringVar you have to use .get() and then dictionary has no problem to find this string

x, y = temp_dict[ temp_var1.get() ]

x, y = temp_dict[ temp_var2.get() ]

the same with Entry but you have to also convert string to float to make calculation

cels = float( temp_entry.get() )  * x + y

Code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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