[英]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.