将用户值存储在条目框中以计算Tkinter中的值

时间:2015-09-11 12:48:37

标签: python tkinter

我正在尝试使用python中的Tkinter从用户输入计算方程式。代码如下:

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()

这里,S_E的值是使用默认值d自动计算的,即0,这是我不想要的。即使我将输入更改为UI中的某个其他值,仍会计算输出的默认值。

我尝试使用自我方法,但我的上司不希望代码变得复杂。如何在不更改源代码的情况下计算S_E的值?

1 个答案:

答案 0 :(得分:2)

你的计算似乎完全没问题。我认为问题是你在不破坏旧标签的情况下继续创建新标签,因此你没有看到新的计算。

创建一次结果标签,然后为每次计算修改它:

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()