Python的GUI执行顺序

2024-03-29 09:38:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我对下面的代码有一些问题。这是我第一次使用GUI,我已经有一段时间没有使用python了。当我尝试用按钮执行solfield函数时,它不会产生任何输出。你知道吗

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

Tags: textinimportmasterbuttonmathcurrentfloat
1条回答
网友
1楼 · 发布于 2024-03-29 09:38:28

问题在于:

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

要将函数solfield本身作为command传递,只需使用其名称:

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

您要做的是调用函数,然后将该函数的返回值作为命令传递。你知道吗

因为您在上面将solfield定义为donothing函数,所以返回值是None,所以您告诉calculate_button它是command=None,并且它正确地不做任何事情。你知道吗


同时,正如塞思莫顿指出的(但随后删除):

You have two functions named solfield, and you are naming a variable solfield in one of your solfield functions. Remove the empty function (the one with pass), and using a different variable name in the remaining function.

这并没有造成你的实际问题,但它无疑会增加困惑,使你更难找到问题。(例如,如果您根本没有包含solfield的多余空定义,那么您会在错误的行中得到一个NameError,这会使调试变得更容易。)


总而言之,你应该做的是:

  1. 去掉solfield的空(pass-only)定义。你知道吗
  2. solfield的实际实现移到构建GUI的位置之上。你知道吗
  3. 不要在函数中命名局部变量solfield。你知道吗
  4. 只传递solfield,而不是作为calculate_buttoncommand。你知道吗

相关问题 更多 >