Why do I get an error in python saying that a method cannot be found even though I previously defined the method?
index = 0
def changeColor():
global index
if index%2==0:
label.configure(bg = "purple")
else:
label.configure(bg = "blue")
index+=1
label.after(1000, changeColor)
de开发者_StackOverflow中文版f Start (self): # command when start button is clicked in GUI
self.root = Tk()
self.root.geometry("500x300")
mainContainer = Frame (self.root)
label = Label(mainContainer, text = "")
label.pack(side = LEFT, ipadx = 5, ipady = 5)
mainContainer.pack()
label.after(1000, changeColor)
self.root.mainloop()
I get an error saying: NameError: global name 'changeColor' is not defined. Why does this occur and how would I fix it?
It looks to me like the problem might be what's not in the snippet. Are both of these functions part of a class definition? From the use of self as an argument in Start, and label in changeColor, it looks like it might be.
If so, let's say it's class Foo, then changeColor is really Foo.changeColor. To use it, you'd pull it outside of the class, or pass it as self.changeColor from Start.
EDIT: Three other things you should do to clean up the style:
- Make changeColor take self as an argument, so it's a proper method of the class.
- Make label a member of the object; i.e. make it self.label, so changeColor can access it.
- Get rid of the global index. Instead, query the label's current color (
self.label['bg']
) to figure out what state it's in.
try this
index = 0
def changeColor(self):
global index
if index%2==0:
self.label.configure(bg = "purple")
else:
self.label.configure(bg = "blue")
index+=1
def Start (self): # command when start button is clicked in GUI
self.root = Tk()
self.root.geometry("500x300")
mainContainer = Frame (self.root)
label = Label(mainContainer, text = "")
label.pack(side = LEFT, ipadx = 5, ipady = 5)
mainContainer.pack()
label.after(1000, self.changeColor)
# above should really be lambda: changeColor()
self.root.mainloop()
working example
>>> def f(): print f
...
>>> def h(f): f()
...
>>> def g(): h(f)
...
>>> g()
<function f at 0x7f2262a8c8c0>
精彩评论