简体   繁体   English

分配2之前引用的局部变量

[英]Local variable referenced before assignment 2

I'm a Python beginner trying the tkinter library. 我是尝试tkinter库的Python初学者。 I am trying to create two text boxes: one will ask for hours and the other for the hourly rate. 我正在尝试创建两个文本框:一个会问几个小时,另一个会问小时费率。 These values will be multiplied. 这些值将相乘。 If the hourly rate is more than 40, it will multiply the hours above 40 by 1.5 to reflect the overtime rate. 如果每小时费率大于40,则它将超过40的小时数乘以1.5以反映加班费率。 I get an error: 我收到一个错误:

UnboundLocalError: local variable 'salary' referenced before assignment

I am not sure if this is the only error in my code. 我不确定这是否是我代码中的唯一错误。 How can I resolve this error? 如何解决此错误?

from tkinter import  *
from tkinter  import ttk

def main():
    value = float(hours.get())
    value2=float(rate.get())
    salary.set(value * value2)
    if hours > 40 : 
        salary = (((hours - 40)* 1.5 ) + 40 )* rate 
    else : 
        salary = hours * rate 
    return salary 

root = Tk()
root.title = ("Salary Calculator")

hours = StringVar()
rate = StringVar()
salary = StringVar()


entry = Entry(root, textvariable=hours)
entry2 = Entry(root, textvariable=rate)
label1=Label(root,textvariable=salary)
label2=Label(root, text='Enter Your Hours Worked: ')
button1=Button(root,text='Calculate Salary',command=main)


entry.pack()
entry2.pack()
label1.pack()
button1.pack()
label2.pack()


root.mainloop()

You don't assign salary before you use it in the local scope: 在本地范围内使用薪水之前,请不要分配薪水:

 salary.set(value * value2) # <- not defined

You set it in the if statements after you have already tried to use it, you are shadowing the salary = StringVar() in the local scope: 在尝试使用它之后,可以在if语句中进行设置,这在本地范围中隐藏了salary = StringVar()

 if hours > 40 :
        salary = (((hours - 40)* 1.5 ) + 40 )* rate # shadows the global salary
    else :
        salary = hours * rate
    return salary

I think you want something more like, which will not cause an error and update the label correctly, you are currently trying to compare StringVar's and and ints: 我认为您想要更多类似的东西,不会导致错误并正确更新标签,您目前正在尝试比较StringVar和and ints:

def main():
    value = float(hours.get())
    value2 = float(rate.get())
    if value > 40 : # compare to .get float not StringVar
        val= (((value - 40)* 1.5 ) + 40 )* value2
    else :
        val = value * value2
    salary.set(val) # set after to whatever val is
    return val

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM