Sandy.Arv
Sandy.Arv

Reputation: 605

Store User Value in an Entry box to calculate a value in Tkinter

I am trying to calculate an equation from user input using Tkinter in python. The code is as follows:

import math

from tkinter import *

def Solar_Param():
   d = Interface.get()
   S_E = 1367*(1 + 0.0334 * math.cos(((math.pi*360)/180) * (d - 2.7206) / 365.25))
   nlabel1 = Label(nGui, text = S_E).pack(side="left")
   return S_E

nGui = Tk()
Interface = IntVar()

nGui.title("Solar Calculations")

nlabel = Label(text = "User Interface for Solar Calculation")
nlabel.pack()

nbutton = Button(nGui, text = "Calculate", command = Solar_Param).pack()
nEntry = Entry(nGui, textvariable = Interface).pack()

nGui.mainloop()

Here, value of S_E is calculated automatically using the default value of d i.e., 0, which I do not want. and even though i change the input to some other value in the UI, the output is still calculated for the default value.

I tried using self method, but my superiors don't want the code to get complex. What should I do to calculate the value for S_E without changing the source code much?

Upvotes: 0

Views: 1267

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386020

Your calculation seems perfectly fine. I think the problem is that you keep creating new labels without destroying the old ones, so you aren't seeing the new calculations.

Create the result label once, and then modify it for each calculation:

import math

from Tkinter import *

def Solar_Param():
   d = Interface.get()
   S_E = 1367*(1 + 0.0334 * math.cos(((math.pi*360)/180) * (d - 2.7206) / 365.25))

   result_label.configure(text=S_E)
   return S_E

nGui = Tk()
Interface = IntVar()

nGui.title("Solar Calculations")

nlabel = Label(text = "User Interface for Solar Calculation")
nlabel.pack()

nbutton = Button(nGui, text = "Calculate", command = Solar_Param).pack()
nEntry = Entry(nGui, textvariable = Interface).pack()

result_label = Label(nGui, text="")
result_label.pack(side="top", fill="x")

nGui.mainloop()

Upvotes: 2

Related Questions