You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

创建英尺英寸转米GUI应用时遭遇TypeError问题求助

问题分析与修复方案

错误原因

你碰到的TypeError: 'module' object is not callable是因为直接把导入的模块function当成函数调用了,正确的做法是调用模块里的convert函数。除此之外,代码还有几个影响功能实现的问题:

  • 获取输入值的方式错误:window['feet']返回的是PySimpleGUI的输入元素对象,不是用户输入的具体数值
  • 未转换输入类型:用户输入的是字符串,直接参与计算会报错
  • 未更新输出标签:计算结果没有显示到界面上
  • 缺失窗口关闭逻辑:循环无法正常终止

分步修复

1. 修正函数调用

把result = function(feet, inches)改成调用模块内的convert函数:

result = function.convert(feet, inches)

2. 正确获取输入数值

通过values字典拿到用户输入的字符串,并转成float类型:

feet = float(values['feet'])
inches = float(values['inches'])

3. 更新界面输出

计算完成后,用update方法把结果显示到输出标签:

window['output'].update(f'{result:.2f} 米')

4. 添窗口关闭逻辑

当用户关闭窗口时(event为None),退出循环并关闭窗口:

while True:
    event, values = window.read()
    if event is None:
        break
    # 仅在点击转换按钮时执行计算
    if event == 'Convert':
        # 后续转换逻辑

完整修正后的主代码

import PySimpleGUI as sg
import functions_feet_meter as function

feet_label = sg.Text('Enter feet: ')
inches_label = sg.Text('Enter inches: ')
feet_input = sg.Input(key='feet')
inches_input = sg.Input(key='inches')
convert_button = sg.Button('Convert')
output_label = sg.Text(key='output')

window = sg.Window('Converter',
                   layout=[[feet_label, feet_input],
                            [inches_label, inches_input],
                            [convert_button, output_label]],
                   font=('Helvetica', 12))

while True:
    event, values = window.read()
    if event is None:
        break
    if event == 'Convert':
        try:
            feet = float(values['feet'])
            inches = float(values['inches'])
            result = function.convert(feet, inches)
            window['output'].update(f'{result:.2f} 米')
        except ValueError:
            window['output'].update('请输入有效数字')

window.close()

额外优化说明

  • 加入try-except块处理非数字输入,避免程序崩溃
  • 结果保留两位小数,显示更规整
  • 仅在点击Convert按钮时执行计算,减少不必要的逻辑触发

内容的提问来源于stack exchange,提问作者mahin04

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 11:20:12