PYTHON: Nameerror: name "..." is not defined, but I defined the function

Asked

Viewed 1,227 times

-1

I’m trying to make a little snake game out of Python. I used the Tkinter library and, to register the pressing of a key, I used the bind() function that executes an event after a key is pressed. I set in the same class several functions to be used in bind, but when I put bind() in the code, I get the following error:

Nameerror: name 'move_up' is not defined

Follows the code:

from tkinter import *
from time import sleep
from threading import Thread

class Game():

    def __init__(self):
        self.window = Tk()
        self.width = 800
        self.height = 600
        self.canvas = Canvas(self.window, width=self.width, height=self.height, bg='black')
        self.canvas.pack()
        self.tamanho = [0, 0, 20, 20]
        self.vel = [0,0,0,0]

    def create_snake(self):
        self.snake = self.canvas.create_rectangle(self.tamanho , fill='white')
        while True:
            self.tamanho = [self.tamanho[0]+ self.vel[0], self.tamanho[1]+self.vel[1], self.tamanho[2] + self.vel[2], self.tamanho[3] +self.vel[3] ]
            print(self.tamanho[0])
            self.canvas.delete('all')
            self.snake = self.canvas.create_rectangle(self.tamanho , fill='white')
            self.window.after(70)
            self.window.update_idletasks()
            self.window.update()
            self.window.bind("<Up>", move_up)
            self.window.bind("<Down>", move_down)
            self.window.bind("<Right>", move_right)
            self.window.bind("<Left>", move_left)  

    def move_right(self, event):
        self.vel = [20,0,20,0]

    def move_down(self, event):
        self.vel = [0, 20, 0, 20]

    def move_left(self, event):
        self.vel = [-20, 0, -20, 0]

    def move_up(self, event):
        self.vel = [0, -20, 0, -20]

t = Game()
t.create_snake()

I cannot understand why the function is not recognized if I have already defined it within the same class. How do I correct this?

1 answer

2

This error is being generated because in fact there is no function called move_up. What you want to call is a method of an object, so you must pass the instance self by calling the function, thus:

        # Código ...

        self.window.bind("<Up>", self.move_up)
        self.window.bind("<Down>", self.move_down)
        self.window.bind("<Right>", self.move_right)
        self.window.bind("<Left>", self.move_left)  

        # Código ...

Not only for methods, but also for attributes. If you create a class and a method like this:

class Pessoa:
    nome = 'Lucas'

    def hello(self):
        print("Olá, meu nome é %s."%nome)

It will not work because you are not passing the instance when trying to use the attribute. Whenever you are going to use an attribute or method, remember to pass the reference of that data.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.