[英]Local variable referenced before assignment 2
我是尝试tkinter库的Python初学者。 我正在尝试创建两个文本框:一个会问几个小时,另一个会问小时费率。 这些值将相乘。 如果每小时费率大于40,则它将超过40的小时数乘以1.5以反映加班费率。 我收到一个错误:
UnboundLocalError: local variable 'salary' referenced before assignment
我不确定这是否是我代码中的唯一错误。 如何解决此错误?
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()
在本地范围内使用薪水之前,请不要分配薪水:
salary.set(value * value2) # <- not defined
在尝试使用它之后,可以在if语句中进行设置,这在本地范围中隐藏了salary = StringVar()
:
if hours > 40 :
salary = (((hours - 40)* 1.5 ) + 40 )* rate # shadows the global salary
else :
salary = hours * rate
return salary
我认为您想要更多类似的东西,不会导致错误并正确更新标签,您目前正在尝试比较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.