An alternative method
from tkinter import *
root = Tk()
root.title('Snake')
root["width"] = 400
root["height"] = 400
field = Canvas(root)
SIZE = 50
class Snake:
def __init__(self,x,y,canvas):
self.x = x
self.y = y
self.canvas = canvas
self.direction = (SIZE,0)
def keypress(self,event):
if event.keysym == 'Right':
self.direction = (SIZE,0)
if event.keysym == 'Left':
self.direction = (-SIZE,0)
if event.keysym == 'Up':
self.direction = (0,-SIZE)
if event.keysym == 'Down':
self.direction = (0,SIZE)
def move(self):
self.x += self.direction[0]
self.y += self.direction[1]
def redraw(self):
self.canvas.delete('snake')
self.move()
self.canvas.create_rectangle(self.x,self.y,self.x+SIZE,self.y+SIZE,fill="green",tag="snake")
def update_screen():
snake.redraw()
root.after(1000,update_screen)
snake = Snake(0,0,field)
root.bind("<KeyPress>", lambda event: snake.keypress(event))
root.after_idle(update_screen)
field.grid()
root.mainloop()
This uses an object for the snake with methods to react to key presses and redraw the snake. This deletes the existing rectangles and draws new ones rather than moving (might prove more useful for showing the different snake segments).
Advantage of this method, is that the snake can be made to move regardless of whether the user has pressed a button or not. If no button has been pressed the snake will continue in the same direction.
Once you have a more complex game, I'd expect your Snake class to contain a list of the different snake segments that get drawn each time. When the snake moves over a fruit, a new segment is added. See below for a moving snake with multiple segments
from tkinter import *
root = Tk()
root.title('Snake')
root["width"] = 400
root["height"] = 400
field = Canvas(root)
SIZE = 10
class Snake:
def __init__(self,x,y,canvas):
self.x = x
self.y = y
self.canvas = canvas
self.direction = (SIZE,0)
self.segments = [(self.x,self.y)]
self.length = 5
def keypress(self,event):
if event.keysym == 'Right':
self.direction = (SIZE,0)
if event.keysym == 'Left':
self.direction = (-SIZE,0)
if event.keysym == 'Up':
self.direction = (0,-SIZE)
if event.keysym == 'Down':
self.direction = (0,SIZE)
def move(self):
self.x += self.direction[0]
self.y += self.direction[1]
new_segment = (self.segments[-1][0]+self.direction[0],self.segments[-1][1]+self.direction[1])
self.segments.append(new_segment)
if len(self.segments) > self.length:
self.segments.pop(0)
def redraw(self):
self.canvas.delete('snake')
self.move()
for seg in self.segments:
self.canvas.create_rectangle(seg[0],seg[1],seg[0]+SIZE,seg[1]+SIZE,fill="green",tag="snake")
#self.canvas.create_rectangle(self.x,self.y,self.x+SIZE,self.y+SIZE,fill="green",tag="snake")
def update_screen():
snake.redraw()
root.after(1000,update_screen)
snake = Snake(0,0,field)
root.bind("<KeyPress>", lambda event: snake.keypress(event))
root.after_idle(update_screen)
field.grid()
root.mainloop()