Global NameError Fix?

Dave Angel davea at davea.name
Fri Mar 22 01:24:17 CET 2013


On 03/21/2013 07:43 PM, maiden129 wrote:
> Hello,
>
> I'm using the version 3.2.3 of Python and I am having an issue in my program and I don't know how to fix it:
>
> counterLabel["text"] = str(counter)
> NameError: global name 'counterLabel' is not defined
>

Please include the entire traceback when reporting an exception.  In 
this case, we can figure it out, but frequently we can't.

> Here is my program:
>
> from tkinter import *
>
>
> class CounterButton(Button):
>
>      def __init__(self, window):
>
>
>         super(CounterButton,self).__init__(window, text = "0", command=self.startCounter)
>
>
>      def startCounter(self):
>          counter = int(self["text"])
>          counter +=1
>          counterLabel["text"] = str(counter)

Where did you think counterLabel was defined?  It needs to be a dict or 
equivalent, in order for you to use the ["text"] notation on it.  If 
it's supposed to be an attribute of the CounterButton, then you should 
create it in the __init__() method, as

         self.counterLabel = {}

And if it's supposed to be inherited from Button (unlikely, with that 
name), presumably it's initialized there.

In either case, if it's supposed to be specific to this instance of 
CounterButton, you need the self. prefix:

             self.counterLabel["text"] = ...

I don't use tkinter, and it's not installed in my Python, but I suspect 
that it is in the Button object, and it's called something else, like text.

Based on a quick internet search, I might try something like:

         self.config(text= str(counter))


This is assuming you actually wanted to change the text on the button 
itself.  You may well want to change something else in your GUI.


>
> window = Tk()
> window.title("counter")
>
>
> counterButton1 = CounterButton(window)
> counterButton2 = CounterButton(window)
>
>
> counterButton1.pack()
> counterButton1.pack()
>
>
> window.mainloop()
>


-- 
DaveA



More information about the Python-list mailing list