Question

I wrote this to create button like functionality using pygame gaming library to learn how to use Python. In using the function push() I get the error "global name 'next' is not defined" when trying to reference an instance variable.

I don't really understand how variables in classes work, I assume the environment is automatically global due to using the self keyboard: it's global by the fact its a member of self. And then anything else is simply in a local scope. I guess that's wrong. So how do I define a "global name" before its used?

Button:

class Button(object):

    def __init__(self,x,y,dimx,dimy,color,phrase):
        self.is_clicked = False
        self.has_next = False
        self.next = None
        self.x=x
        self.y=y
        self.dim_x=dimx
        self.dim_y=dimy
        self.e_x=x+dimx
        self.e_y=y+dimy
        self.color=color
        self.color2=color
        self.phrase=phrase

    def mypush(self,btn):
        if not (self.has_next):
            self.next=btn
            self.has_next=True
        else:
            next.mypush(btn)   """ === right here === """

    def checkhit(self,x,y):
         if ((x>= self.x) or (x<=self.e_x)):
             if((y>= self.y) or (y<=self.e_y)):
                 self.is_clicked = True
             self.color = (255,255,255)
                 return self.phrase
         elif (self.has_next == True):
             return self.next.checkhit(x,y)
         else:
             return None

    def release(self):
        if(self.is_clicked == True):
             self.is_clicked=False
         self.color=self.color2
        elif(self.has_next == True):
            self.next.release()

    def mydraw(self,the_game,scrn):
        the_game.draw.rect(scrn,self.color,[self.x, self.y, self.dim_x,self.dim_y])
        if(self.has_next):
            self.next.mydraw(the_game,scrn)
    ...

Where function push is used:

for x in range(2, 10):
    btn = Button(10+50*x,470,45,20,(128,64,224),"Button ".join(num[x-1]))
    my_button.mypush(btn)

result:

Traceback (most recent call last):
  File "testbutton1.py", line 83, in <module>
    my_button.mypush(btn)
  File "testbutton1.py", line 22, in mypush
    next.mypush(btn)
NameError: global name 'next' is not defined
Was it helpful?

Solution

you need to refer to the member variable

self.next.mypush(btn)

not the global variable

next
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top