在PySimpleGUI中使用输入键值计算遇TypeError的问题求助
PySimpleGUI 计算功能报错:TypeError: 'dict' object is not callable
问题代码
import PySimpleGUI as sg def fixedDepositCalc1(): layout = [ [sg.Text("What is your principle amount?:")], [sg.I(key='-PRINCIPLE-')], [sg.Text("What is your interest rate for your deposit? Please give your answer in a percent form:")], [sg.I(key='-RATE-')], [sg.Text("What is the tenure for your fixed deposit?:")], [sg.I(key='-TIME-')], [sg.B("Ok")] ] window4 = sg.Window("Fixed Deposit Calculator - Financial Manager").Layout(layout) event, values = window4.read() if event == "Ok": I_MONEY = float(values('-PRINCIPLE-')) * float((values('-RATE-')/100)) * float(values('TIME')) P_MONEY = float(values('-PRINCPLE-')) + I_MONEY global principle principle = float(values='-PRINCIPLE-') layout2 = [ [sg.T(f"Your principle amount is{principle}")] ] window5 = sg.Window("Fixed Deposit Calculator - Financial Manager").Layout(layout2) event, values = window5.read()
报错信息
File "c:\Users\Kashyap\Desktop\pysimplegui\fixedDepositCalc.py", line 19, in fixedDepositCalc1 I_MONEY = float(values('-PRINCIPLE-')) * float((values('-RATE-')/100)) * float(values('TIME')) TypeError: 'dict' object is not callable
错误原因
- 字典访问语法错误:
values是PySimpleGUI返回的字典对象,必须用方括号[]访问键值,你多处错误使用了圆括号()(比如values('TIME'))。 - 拼写错误:
values('-PRINCPLE-')里的键名少写了一个字母I,正确应为-PRINCIPLE-。 - 赋值语法错误:
principle = float(values='-PRINCIPLE-')混淆了赋值符号与字典访问语法,正确写法是float(values['-PRINCIPLE-'])。 - 未处理异常分支:若用户未点击"Ok"直接关闭窗口,
principle变量未定义,会导致第二个窗口创建失败。
修正后的代码
import PySimpleGUI as sg def fixedDepositCalc1(): layout = [ [sg.Text("What is your principle amount?:")], [sg.Input(key='-PRINCIPLE-')], [sg.Text("What is your interest rate for your deposit? Please give your answer in a percent form:")], [sg.Input(key='-RATE-')], [sg.Text("What is the tenure for your fixed deposit?:")], [sg.Input(key='-TIME-')], [sg.Button("Ok")] ] window4 = sg.Window("Fixed Deposit Calculator - Financial Manager", layout) event, values = window4.read() window4.close() # 关闭窗口释放资源 if event == "Ok": try: # 正确访问字典值,修正拼写错误 principle = float(values['-PRINCIPLE-']) rate = float(values['-RATE-']) / 100 time = float(values['-TIME-']) interest = principle * rate * time total_amount = principle + interest # 展示完整计算结果 layout2 = [ [sg.Text(f"Principle amount: {principle}")], [sg.Text(f"Interest earned: {interest:.2f}")], [sg.Text(f"Total amount after tenure: {total_amount:.2f}")], [sg.Button("Close")] ] window5 = sg.Window("Fixed Deposit Calculator - Results", layout2) window5.read() window5.close() except ValueError: # 处理非数字输入的情况 sg.popup_error("Please enter valid numeric values!") else: # 处理用户取消操作的情况 sg.popup("Operation cancelled.") fixedDepositCalc1() # 调用执行函数
修正说明
- 统一使用
values[key]语法访问输入值 - 修正键名拼写错误
- 添加窗口关闭操作,避免资源占用
- 增加异常处理,防止非数字输入导致崩溃
- 补充展示利息和本息总额,完善功能
- 调用函数确保代码可执行
内容的提问来源于stack exchange,提问作者kishore sukshavasi
相关产品推荐
相关产品推荐

