2013-05-14 34 views
1

我在使用下面的代碼時遇到了一些問題。這是我第一次使用GUI,並且自從我使用python以來已經有一段時間了。當我嘗試用按鈕執行solfield功能時,它不會輸出。使用GUI的Python執行順序

from Tkinter import * 
import math 

master = Tk() 

n = float() 
I = float() 


def solfield(): 
    pass 



label_coils = Label(text='Number of Coils Per Meter', textvariable=n) 
label_coils.grid() 
coils = Entry(master) 
coils.grid() 

label_current = Label(text='Current in Amps', textvariable=I) 
label_current.grid() 
current = Entry(master) 
current.grid() 

calculate_button = Button(text='Calculate', command=solfield()) 
calculate_button.grid() 
label_bfield = Label(text='B Field in +z Direction') 
label_bfield.grid() 
label_result = Label(text='solfield') 
label_result.grid() 


master.title('Coil Gun Simulation') 
master.mainloop() 


def solfield(): 
    mu0 = math.pi*4e-7 
    solfield = mu0*n*I 
    print solfield 

任何其他技巧也將不勝感激,因爲最終會有更多的編碼爲我做。

這已經解決了。如果有人有興趣,這裏是幾個修復了代碼之後:

from Tkinter import * 
import math 

master = Tk() 

label_coils = Label(text='Number of Coils Per Meter') 
label_coils.grid() 
coils = Entry(master) 
coils.grid() 

label_current = Label(text='Current in Amps') 
label_current.grid() 
current = Entry(master) 
current.grid() 



def solfield(): 
    mu0 = math.pi*4e-7 
    n = float(coils.get()) 
    I = float(current.get()) 
    fieldmag = mu0*n*I 
    print fieldmag 

calculate_button = Button(text='Calculate', command=solfield) 
calculate_button.grid() 
label_bfield = Label(text='B Field in +z Direction') 
label_bfield.grid() 
label_result = Label(text='solfield') 
label_result.grid() 



master.title('Coil Gun Simulation') 
master.mainloop() 
+1

您應該在'solfield'函數中使用與'solfield'不同的變量名稱。這很可能會給你帶來問題。 – SethMMorton

+0

另一方面,'n = float()'與'n = 0.0'相同,首先這樣做確實沒有什麼好的理由。我不認爲你需要一個全局變量。如果你這樣做,你可能不希望它是0(否則'solfield()'將總是打印'0' ...)。所以,大概你會在某個時候設定一個「真正的價值」。如果是這樣,你不需要先將其設置爲float(),然後再將其設置爲實際值。 Python不要求你「在頂部聲明變量」,如C. – abarnert

回答

2

的問題是在這裏:

calculate_button = Button(text='Calculate', command=solfield()) 

傳遞給函數solfield本身作爲command,只要使用它的名字:

calculate_button = Button(text='Calculate', command=solfield) 

你在做什麼是調用該函數,然後傳遞該函數的返回值作爲命令。

既然你上面什麼都不做的函數定義solfield,即返回值是None,讓你告訴calculate_buttoncommand=None,和它的正確無所事事。


同時,作爲SethMMorton指出,(但後來刪除):

您有一個名爲solfield兩個功能,而你在你的solfield功能之一命名的變量solfield。刪除空函數(帶有合格的函數),並在其餘函數中使用不同的變量名稱。

這不會導致您的實際問題,但它肯定增加,使得它很難爲你找到這個問題的困惑。 (例如,如果你沒有包括的solfield多餘的空定義可言,你會得到不正確的線NameError,這將讓事情更容易調試。)


將所有內容同時,你應該做的是:

  1. 擺脫solfield空(pass - 只)的定義。
  2. solfield的實際實現向上移動到構建GUI的點上方。
  3. 請勿在函數中命名本地變量solfield
  4. 只通過solfield而不是solfield()作爲command對於calculate_button
+0

這是問題的一部分。另一部分是他們沒有定義'solfield'直到主循環退出之後。 –

+1

他在使用它之後定義了'solfield' *。他很可能認爲他需要像'C'這樣的函數聲明。我認爲把定義移到「聲明」的位置會有所幫助。 – SethMMorton

+0

@BryanOakley:對不起,我正在迅速重寫我的答案,以便將Seth的所有觀點都納入我的答案中(因爲他刪除了他的評論並且是答案,但他們很重要)。目前的版本看起來不錯嗎? – abarnert