gdn
gdn

Reputation: 39

Python/Tkinter - add

I'm developing an application to add the two fields, but instead of adding, it is concatenating. can you help me? Follow the code below:

from tkinter import *

root = Tk()


l_vlrRec = Label(root, text='Receita')
l_vlrRec.place(x=10, y=10)
e_vlrRec = Entry(root)
e_vlrRec.place(x=75, y=10, width=75)

l_vlrCar = Label(root, text='Receita 2')
l_vlrCar.place(x=10, y=30)
e_vlrCar = Entry(root)
e_vlrCar.place(x=75, y=30, width=75)

v_result = DoubleVar()
l_result = Label(root, textvariable=v_result)
l_result.place(x=10, y=150)


def calcular():


    v_result.set(round(float(e_vlrRec.get() + e_vlrCar.get()), 2))
    e_vlrRec.delete(0, END)
    e_vlrCar.delete(0, END)


bt = Button(root, text='Calcular', command=calcular)
bt.place(x=10, y=50)

root.mainloop()

Upvotes: 0

Views: 54

Answers (2)

miw
miw

Reputation: 764

Generally, a plus sign is addition for numbers and concatenation for strings. GUI elements like textboxes treat their values as strings mostly.

In your case it seems that the parentheses in the calculation need to be adjusted so that

  • first the values are converted to floats

  • they are added then.

In your code:

float(e_vlrRec.get()) + float(e_vlrCar.get())

should return the sum of the 2 values as a float. Your version first concatenated the 2 strings and then converts the result to float.

Upvotes: 1

chuck
chuck

Reputation: 1447

You're adding the strings and then converting to float. You need to first convert each string to float individually:

def calcular():
    v_result.set(round(float(e_vlrRec.get()) + float(e_vlrCar.get()), 2))
    e_vlrRec.delete(0, END)
    e_vlrCar.delete(0, END)

Upvotes: 2

Related Questions