Search code examples
pythontypeerrorpysimplegui

TypeError while creating a GUI app to convert feet and inches to meters


I am creating a python GUI app to convert feet and inches into meters. My function is in a different file from my main code file.

This is my function file: which is named - functions_feet_meter.py

def convert(feet, inches):
    meter = feet*0.3048 + inches*0.0254
    return meter

This is my main code file -

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()
    print('EVENT', event)
    print('VALUES', values)

    feet = window['feet']
    inches = window['inches']
    result = function(feet, inches)

window.close()

This is the error which is shown -


Traceback (most recent call last):
  File "F:\Py\app1\Bonus\feet_inches to meter.py", line 25, in <module>
    result = function(feet, inches)
TypeError: 'module' object is not callable

Process finished with exit code 1

I expect the user will input feet and inches in the GUI app and it will show meters right by the convert button

I expect the user will input feet and inches in the GUI app and it will show meters right by the convert button


Solution

  • import binds a module or one of its contained objects to a name. Usually it uses the same name as the thing being imported but as lets you change that name.

    import functions_feet_meter as function
    

    imports the module but binds that module to the variable function. You want the convert function inside the module. Since it would be uncommon to rename that function "function", you likely want

    from functions_feet_meter import convert
    

    This imports the module and then binds its contained "convert" object instead of the module itself. And then you'd use "convert" instead of "function" later. You could also do

    from functions_feet_meter import convert as function
    

    if you really like that function name.