Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #41681

Re: Global NameError Fix?

Date 2013-03-21 20:24 -0400
From Dave Angel <davea@davea.name>
Subject Re: Global NameError Fix?
References <44451203-05be-4336-9325-c956b0ee2116@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.3608.1363911877.2939.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Global NameError Fix? maiden129 <sengokubasarafever@gmail.com> - 2013-03-21 16:43 -0700
  Re: Global NameError Fix? Dave Angel <davea@davea.name> - 2013-03-21 20:24 -0400
    Re: Global NameError Fix? Rick Johnson <rantingrickjohnson@gmail.com> - 2013-03-22 10:21 -0700
  Re: Global NameError Fix? David Robinow <drobinow@gmail.com> - 2013-03-21 21:04 -0400

csiph-web