我在使用下面的代碼時遇到了一些問題。這是我第一次使用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()
您應該在'solfield'函數中使用與'solfield'不同的變量名稱。這很可能會給你帶來問題。 – SethMMorton
另一方面,'n = float()'與'n = 0.0'相同,首先這樣做確實沒有什麼好的理由。我不認爲你需要一個全局變量。如果你這樣做,你可能不希望它是0(否則'solfield()'將總是打印'0' ...)。所以,大概你會在某個時候設定一個「真正的價值」。如果是這樣,你不需要先將其設置爲float(),然後再將其設置爲實際值。 Python不要求你「在頂部聲明變量」,如C. – abarnert