2013-05-14 31 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