如何处理“StringVar”类型的Python

2024-09-28 17:05:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个代码,可以将温度单位转换为其他温度单位,例如摄氏度到华氏度。当我运行这段代码时,我得到一个错误,说明类型错误:unhashable type 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

Tags: texttkintercolumntempdicttkgridrow
1条回答
网友
1楼 · 发布于 2024-09-28 17:05:37

要从StringVar获取字符串,必须使用.get(),这样字典就可以找到这个字符串了

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

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

Entry相同,但还必须将字符串转换为float才能进行计算

^{pr2}$

代码:

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

相关问题 更多 >