“ UnboundLocalError:分配前已引用局部变量'TimerOnOff'”

时间:2019-11-23 11:58:57

标签: python

有人可以帮助我解决此问题吗?运行该程序时,出现错误“ 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()

1 个答案:

答案 0 :(得分:0)

如果要在函数中使用TimerOnOffTimer之类的全局变量,则需要添加一条语句以指定您正在局部范围内使用全局变量。所以你需要添加

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()