如何使这个变量全局化,以便它可以在所有函数中使用

时间:2016-06-23 11:44:45

标签: python function tkinter global-variables

我使用t作为全局,并从ts1函数中分配s2值 但在person1之后,它不会person2。错误如下

File "C:\Users\Teja kaipa\Desktop\estimation.py", line 42, in person1
if (t>1):
    NameError: name 't' is not defined
global t

代码:

def s1():
    t=1
    return t
def s2():
    t=2
    return t
def s3():
    t=3

def person1():
    output = 0
    val1 = int(r1e1.get())
    val2 = int(r1w1.get())
    if ((val1-val2)==0):
        output = 1+2*val1
    else:
        output = -2*abs(val1-val2)
    r1n1m.delete(0, END)
    r1n1m.insert(4,str(output))    
    if (t>1):
        person2()

def person2():
    val1= int(r1e2.get())
    val2= int(r1w2.get())
    if ((val1-val2)==0):
        output = 1+2*val1
    else:
        output = -2*abs(val1-val2)
    r1n2m.delete(0, END)
    r1n2m.insert(4,str(output))    
    if (t>2):
        person3()

1 个答案:

答案 0 :(得分:1)

在要修改全局变量的每个模块中,显式指定t作为全局变量。

def func1():
    global t
    t = 3

def func2():
    global t
    t = [1,2,3]

def main():
    global t
    func1()
    print t
    func2()
    print t

输出应为:

3
[1, 2, 3]