tags:

views:

89

answers:

2
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?

A: 

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>
aaa
sorry, still doesnt work
samuel
@sam error is ...?
aaa
it is the same error
samuel
@sam look for mistakes elsewhere, for example `label` is undefined
aaa
hmm.. see when i delete the def Start (self) and leave all the code from self.root = Tk() to self.root.mainloop() after it by itself, then my program worksany ideas about this?
samuel
@sam are this functions inside class!?
aaa
yes they are in the class
samuel
@sam see corrections in my post, be aware you most likely will get other errors
aaa
+2  A: 

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.
Owen S.