使用PySimpleGUI开发复利计算器时结果始终为0.00的问题
复利计算器GUI问题修复
问题根源
- PySimpleGUI输入框默认不会触发事件,原代码中
match event里的'principles'、'rates'、'times'事件永远不会被触发,导致principle、rate、time始终保持初始值0,计算结果自然为0.00。 - 错误地尝试将输入框对象(如
principleInput)直接转为数值类型,正确做法是从window.read()返回的values字典中读取对应key的输入字符串。 - 输入验证逻辑位置错误,应该在用户点击「Complete」按钮时统一获取并验证输入值,而非监听未启用的输入框事件。
- 退出条件中的
"OK"按钮不存在,代码里没有该按钮,无需判断。
修正后的代码
# 复利计算器GUI import PySimpleGUI as sg def main(): # 初始化变量 principle = 0.0 rate = 0.0 time = 0 # 界面元素定义 principleInputText = sg.Text("Enter principle amount: ") principleInput = sg.InputText(key="principles") rateInputText = sg.Text("Enter interest rate: ") rateInput = sg.InputText(key='rates') timeInputText = sg.Text("Enter time in years: ") timeInput = sg.InputText(key='times') complete_button = sg.Button("Complete") output_label = sg.Text(key='output', text_color="black") layout = [[principleInputText, principleInput], [rateInputText, rateInput], [timeInputText, timeInput], [complete_button], [output_label]] window = sg.Window(title="Compound Interest Calculator", layout=layout) while True: event, values = window.read() # 关闭窗口时退出循环 if event == sg.WIN_CLOSED: break if event == 'Complete': # 获取并验证输入值 valid = True try: principle = float(values['principles']) if principle <= 0: sg.popup_error("本金不能小于或等于0") valid = False except ValueError: sg.popup_error("请输入有效的本金数值") valid = False try: rate = float(values['rates']) if rate <= 0: sg.popup_error("利率不能小于或等于0") valid = False except ValueError: sg.popup_error("请输入有效的利率数值") valid = False try: time = int(values['times']) if time <= 0: sg.popup_error("年限不能小于或等于0") valid = False except ValueError: sg.popup_error("请输入有效的年限整数") valid = False # 验证通过后计算并显示结果 if valid: total = principle * pow((1 + rate / 100), time) window['output'].update(value=f'{time}年后本息总额: ${total:.2f}') if __name__ == "__main__": main()
关键修改说明
- 移除了无效的输入框事件监听,改为在点击「Complete」时统一处理输入。
- 通过
values[key]获取用户输入的字符串,并转为对应数值类型,同时添加异常捕获处理非数值输入。 - 使用
sg.popup_error替代控制台打印,给用户更直观的GUI错误提示。 - 修正了退出条件,只判断窗口关闭事件。
- 调整了结果显示的字符串格式,更清晰直观。
内容的提问来源于stack exchange,提问作者Nelson Malbone
相关产品推荐
相关产品推荐

