When I run the command decimal is not getting printed by Python tkinter

Viewed 55
from tkinter import *
from functools import partial
wn=Tk()
wn.geometry("400x200")
wn.configure(bg='green')


def add(r,a,b,y):
    a=(a.get())# input("first number:=")
    b=(b.get())#input("\nsecond number:=")
    y=(y.get())
    c=float(a)*float(b)*float(y)/100
    r.config(text="Result = %d" % c)
    return
#print("the sum of numbers=",format(c))


l=Label(wn,text="Simple Interest",border=0).grid(row=1,column=2)
l2=Label(wn,text="Enter principal amount",border=0).grid(row=2,column=1)
l3=Label(wn,text="rate of Interest",border=0).grid(row=3,column=1)
l4=Label(wn,text="Enter no. of year",border=0).grid(row=4,column=1)
r =Label(wn)
r.grid(row=7, column=2)

number1 =StringVar()
number2 =StringVar()
number3 =StringVar()

Num1 = Entry(wn, textvariable=number1).grid(row=2, column=2)
Num2 = Entry(wn, textvariable=number2).grid(row=3, column=2)
Num2 = Entry(wn, textvariable=number3).grid(row=4, column=2)

add = partial(add,r, number1, number2,number3)
but_r= Button(wn, text="Calculate", command=add).grid(row=5, column=1)
wn.mainloop()

When I pass in the value 5 in all places, the answer has to be 1.25 but it is showing 1.

I have have tried a lot but I didn't get the solution so please help me to solve this issue

2 Answers

Small mistake, in the r.config, change the %d to %f and it will give a floating point value:

from tkinter import *
from functools import partial
wn=Tk()
wn.geometry("400x200")
wn.configure(bg='green')


def add(r,a,b,y):
    a=(a.get())# input("first number:=")
    b=(b.get())#input("\nsecond number:=")
    y=(y.get())
    c=float(a)*float(b)*float(y)/100
    r.config(text="Result = %f" % c)
    return
#print("the sum of numbers=",format(c))


l=Label(wn,text="Simple Interest",border=0).grid(row=1,column=2)
l2=Label(wn,text="Enter principal amount",border=0).grid(row=2,column=1)
l3=Label(wn,text="rate of Interest",border=0).grid(row=3,column=1)
l4=Label(wn,text="Enter no. of year",border=0).grid(row=4,column=1)
r =Label(wn)
r.grid(row=7, column=2)

number1 =StringVar()
number2 =StringVar()
number3 =StringVar()

Num1 = Entry(wn, textvariable=number1).grid(row=2, column=2)
Num2 = Entry(wn, textvariable=number2).grid(row=3, column=2)
Num2 = Entry(wn, textvariable=number3).grid(row=4, column=2)

add = partial(add,r, number1, number2,number3)
but_r= Button(wn, text="Calculate", command=add).grid(row=5, column=1)
wn.mainloop()

The above code will print something like 1.250000. If you want to get exact 2 decimal points like 1.25, use:

r.config(text="Result =" + str(round(c, 2)))

Hope it helps :)

change your add function too -

def add(r,a,b,y):
    a=(a.get())# input("first number:=")
    b=(b.get())#input("\nsecond number:=")
    y=(y.get())
    c=float(a)*float(b)*float(y)/100
    r.config(text="Result = %.3f" %c)
    return

%f is for floats anad %.3f limits it to 3 decimal places which is a bit cleaner than the default value

Related