我正在尝试更改从Tkinter按钮调用的函数中的'number',如下面function2
中所示。 function1
识别“号码”并且工作正常,function2
给出UnboundLocalError
。如果我尝试传递Button中的值(如:command=function2(number)
),则无需按下按钮即可立即执行该功能。有人可以帮忙吗?
from tkinter import *
def function1():
print('In pcomm.')
print('number=', str(number))
def function2():
print('In acomm.')
print('number=', str(number))
number += 1 #UnboundLocalError: local variable 'number' referenced before assignment
print('number=', str(number))
#create the window
root = Tk()
number = 2
print('Just assigned: number=', str(number))
printButton = Button(root, text = "Press to print.", command = function1).grid()
addButton = Button(root, text = "Press for number+=1.", command = function2).grid()
#kick off the event loop
root.mainloop()
答案 0 :(得分:1)
要避免全局,您需要使用类。
class AppData(object):
def __init__(self):
self.number = 2
def function1(self):
print('In pcomm.')
print('number=', str(self.number))
def function2(self):
print('In acomm.')
print('number=', str(self.number))
self.number += 1
print('number=', str(self.number))
然后,您将创建该类的实例,并将其绑定方法传递给按钮...
app = AppData()
addButton = Button(root, text = "Press for number+=1.", command = app.function2)
addButton.grid()
请注意,您经常会将该按钮视为另一个(或相同)类的一部分。