有人可以帮助我解决此问题吗?运行该程序时,出现错误“ UnboundLocalError:分配前引用了本地变量'TimerOnOff'”
TimerOnOff = 0
Timer = 7.5
class Timeout():
def start():
Timer = 7.5
if TimerOnOff == 1:
for T in range(0, 75):
Timer - 0.1
time.sleep(0.1)
print(Timer)
TimerOnOff = 0
TimerOnOff = 1
Timeout.start()
答案 0 :(得分:0)
如果要在函数中使用TimerOnOff
或Timer
之类的全局变量,则需要添加一条语句以指定您正在局部范围内使用全局变量。所以你需要添加
global TimerOnOff
global Timer
在您的功能主体中。完整的实现将是:
import time
TimerOnOff = 0
Timer = 7.5
class Timeout():
def start():
global TimerOnOff
global Timer
Timer = 7.5
if TimerOnOff == 1:
for T in range(0, 75):
Timer - 0.1
time.sleep(0.1)
print(Timer)
TimerOnOff = 0
TimerOnOff = 1
Timeout.start()