Skip to main content
 首页 » 编程设计

python之赋值前引用的变量之Python

2025年05月04日13Renyi-Fan

我收到错误...

a = a + b 
UnboundLocalError: local variable 'a' referenced before assignment 

一开始就给a和b两个变量赋值,不明白为什么会报错。

from tkinter import * 
 
a = 10 
b = 12 
def stopProg(e): 
    root.destroy() 
 
def addNumbers(e): 
    a = a + b 
    label1.configure(text= str(a)) 
 
root=Tk() 
button1=Button(root,text="Exit") 
button1.pack() 
button1.bind('<Button-1>',stopProg) 
button2=Button(root,text="Add numbers") 
button2.pack() 
button2.bind('<Button-1>',addNumbers) 
label1=Label(root,text="Amount") 
label1.pack() 
 
root.mainloop() 

请您参考如下方法:

无论何时在函数中修改全局变量,都需要先将该变量声明为全局变量。

因此,您需要对全局变量 a 执行此操作,因为您在 addNumbers 中修改了它:

def addNumbers(e): 
    global a 
    # This is the same as: a = a + b 
    a += b 
    # You don't need str here 
    label1.configure(text=a) 

这是关于 global 的引用关键字。


此外,我想指出,如果您使用 Button 的 command 选项,您的代码可以得到改进:

from tkinter import * 
 
a = 10 
b = 12 
def stopProg(): 
    root.destroy() 
 
def addNumbers(): 
    global a 
    a += b 
    label1.configure(text=a) 
 
root=Tk() 
button1=Button(root, text="Exit", command=stopProg) 
button1.pack() 
button2=Button(root, text="Add numbers", command=addNumbers) 
button2.pack() 
label1=Label(root, text="Amount") 
label1.pack() 
 
root.mainloop() 

没有充分的理由使用绑定(bind)来代替 command 选项。