2015-09-11 38 views
0

我正試圖從python中使用Tkinter的用戶輸入計算公式。代碼如下:將用戶值存儲在輸入框中以計算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的值而不用更改源代碼?

+0

首先請閱讀:http://stackoverflow.com/questions/21592630/why-do-my-tkinter-widgets- get-stored-as-none –

+0

@EricLevieil:雖然這是很好的建議,但它與問題中的問題無關。 –

回答

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

現在我看到..它的完美..感謝您的幫助! –