gpt4 book ai didi

带 GUI 的 Python 执行顺序

转载 作者:行者123 更新时间:2023-12-01 05:44:27 25 4
gpt4 key购买 nike

我在使用以下代码时遇到一些问题。这是我第一次使用 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()

最佳答案

问题出在这里:

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

要将函数 solfield 本身作为命令传递,只需使用它的名称:

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

您正在做的是调用该函数,然后将该函数的返回值作为命令传递。

由于您将上面的 solfield 定义为不执行任何操作的函数,因此返回值为 None,因此您告诉 calculate_button 它的 command=None,它实际上什么也不做。

<小时/>

同时,正如 SethMMorton 指出的那样(但随后被删除):

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)定义。
  2. solfield 的实际实现移至构建 GUI 的位置之上。
  3. 不要在函数内命名局部变量 solfield
  4. 仅传递 solfield,而不是 solfield() 作为 calculate_button命令

关于带 GUI 的 Python 执行顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16554325/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com