【问题标题】:"Local variable referenced before assignment" error“分配前引用的局部变量”错误
【发布时间】:2018-07-16 03:55:48
【问题描述】:

我的代码出现“赋值前引用的局部变量'答案'”错误。我应该如何解决这个问题?

from Tkinter import *
import Tkinter


def proces():

  F=Entry.get(E1)
  m=Entry.get(E2)
  a=Entry.get(E3)
  if F ==0:
      answer=float(m)*float(a)
  if m ==0:       
      answer=float(F)/float(a)
  if a ==0:
      answer=float(F)/float(m)
  Entry.insert(E4,0,answer)
  print(answer)

#And the rest of the GUI coding goes here. 

top = Tkinter.Tk()
L1 = Label(top, text="My calculator",).grid(row=0,column=1)
L2 = Label(top, text="Force",).grid(row=1,column=0)
L3 = Label(top, text="Weight",).grid(row=2,column=0)
L4 = Label(top, text="Accelaration",).grid(row=3,column=0)
L4 = Label(top, text="Solution",).grid(row=4,column=0)
E1 = Entry(top, bd =5)
E1.grid(row=1,column=1)
E2 = Entry(top, bd =5)
E2.grid(row=2,column=1)
E3 = Entry(top, bd =5)
E3.grid(row=3,column=1)
E4 = Entry(top, bd =5)
E4.grid(row=4,column=1)
B=Button(top, text ="Solve",command = proces).grid(row=5,column=1,)

top.mainloop()

【问题讨论】:

标签: python user-interface tkinter


【解决方案1】:

这样给:

answer = "the value which you can give as default"
if F ==0:
  answer=float(m)*float(a)
if m ==0:       
  answer=float(F)/float(a)
if a ==0:
  answer=float(F)/float(m)

或

if F ==0:
  answer=float(m)*float(a)
elif m ==0:       
  answer=float(F)/float(a)
elif a ==0:
  answer=float(F)/float(m)
else :
  answer = "the value which you can give as default"

如果没有一个条件与您要分配给answer 的值匹配?您可以在上述答案中提到的地方给出的值

【讨论】:

  • 不,答案是“0”
  • 您的其他价值观是什么?尝试在每个 if 中打印答案并检查它
  • 尝试在每个 if 之后打印答案。然后我在 3 个字段中的 2 个中输入 2 个数字并按解决后什么也没有发生。任何帮助”?
  • 我可以帮助您,但需要知道您传递给 F,m 和 a 的值是什么?
  • 这是答案。
【解决方案2】:

非常感谢您的快速回复。

我终于解决了。

我所要做的就是制作 如果(变量)==0: 到 如果 len(变量)==0:

我希望以后遇到这个问题的人会觉得这很有帮助。

【讨论】:

    【解决方案3】:

    您在 if 语句中为变量“answer”赋值,因此其范围仅限于那些 if 语句,只需在 if 语句之前初始化变量 answer。

    【讨论】:

    • 你能告诉我怎么做吗? , Cus 当我在 is 语句之前分配 'answer=0' 时,solution(answer) 总是打印为 0。
    • 在初始化 answer=0 之后如果最后得到 '0' 作为答案,这意味着没有执行任何 if 条件,所以你必须检查你传递给的值F,m,a。
    猜你喜欢
    • 2014-08-20
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-07
    • 2021-10-25
    相关资源
    最近更新 更多