-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?
WOW! THANK YOU VERY MUCH
– Guilherme Gomes