Home > Software engineering >  TypeError: unsupported operand type(s) for *: 'Entry' and 'float'
TypeError: unsupported operand type(s) for *: 'Entry' and 'float'

Time:03-25

Ok, so I have a family member who is learning Python. I myself don't know Python besides Hello World. She has made a code with tkinter and it keeps returning the error mentioned in the title. This is the code:

from tkinter import*
def time():
    m=input1
    g=9.81
    h=input2
    P=input3
    time=m*g*h/P
    time=Label(window1, text="Time is" str(time))
    time.place(x=130, y=230)
window1=Tk()
window1.title("TASK 1")
window1.geometry("300x300")

output1=Label(window1, text="WORK-POWER-ENERGY")
output1.place(x=70, y=20)

output2=Label(window1, text="Mass of the object (t):")
output2.place(x=40,y=60)

input1=Entry(window1)
input1.place(x=160,y=60, width=80)

output3=Label(window1,text="Height of lifting (m):")
output3.place(x=20,y=100)

input2=Entry(window1)
input2.place(x=160, y=100, width=80)

output4=Label(window1,text="Power of the elevator (kW):")
output4.place(x=10,y=140)

input3=Entry(window1)
input3.place(x=160, y=140, width=80)

button1=Button(window1,text="Calculate", command=time)
button1.place(x=150,y=180)

So this is the code (don't mind my attempt of translating the whole code to English.)

I've tried Googling for answers but nothing came up. To my knowledge the program should output the result below the button in the window.

The error that I constantly get is this:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\spaji\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "D:/Korisnici/spaji/Radna površina/programmm.py", line 7, in time
    time=m*g*h/P
TypeError: unsupported operand type(s) for *: 'Entry' and 'float'

CodePudding user response:

You have to use the get method to extract the value stored in the Entry object (then parse that string appropriately). For example,

m = float(input1.get())

CodePudding user response:

m=input1
g=9.81
h=input2
P=input3
time=m*g*h/P

Can you see this lines? g is a float, while h, m and P are tkinter.Entry objects, you can't multiply them.


You can multiply them this way:

m = input1.get() # You get the content of input1 as a string
m = float(m) # You convert it to a float

...and doing this with h and P.

CodePudding user response:

input1, input2 and input3 variables are of type Entry - they represent the whole input bar, not value of whatever is typed into it. You can't multiply UI element by a number because it doesn't make sense. If you want a value itself you need a .get() method (returns a string - if you want a number you have to do another conversion).

https://www.tutorialspoint.com/python/tk_entry.htm

  • Related