Reputation: 11
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)
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, 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?
Upvotes: 0
Views: 154
Reputation: 7855
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:
self.label['bg']
) to figure out what state it's in.Upvotes: 2
Reputation: 51465
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>
Upvotes: 0