0

I'm trying to make snake in Python with Tkinter. Because I want to minimize the amount of external libraries, I tried to make functions that are activated with tk.bind and change the direction of the snake. First I wanted to see, if that works, so I programmed the functions to print 'up', 'left', ..., and that worked. Than I programmed the functions to change the direction-variable and than print the value in the mainloop. But that didn't work. I don't really know how to fix it, but I assume it has something to do with how things are updated.

The code:

from tkinter import *
import time
import random

tk = Tk()



tk.title('Snake')
tk.resizable(0, 0)
root = Canvas(tk, bg='black', height=640, width=1024)

dir_snake = 'right'

def chdir_w(event):
  dir_snake = 'up'
  #print('up')
def chdir_a(event):
  dir_snake = 'left'
  #print('left')
def chdir_s(event):
  dir_snake = 'down'
  #print('down')
def chdir_d(event):
  dir_snake = 'right'
  #print('right')
tk.bind('w', chdir_w)
tk.bind('a', chdir_a)
tk.bind('s', chdir_s)
tk.bind('d', chdir_d)


class Snake_Tile:
    def __init__(self, startpos):
        self.body = root.create_rectangle(startpos[0], startpos[1], startpos[0] + 64, //
startpos[1] + 64, outline='green', fill='green')

    def move_to(self, pos):
        root.move(self.body, pos[0], pos[1])


snake_body = [0]
#snake_body[0] = root.create_rectangle(512, 320, 576, 384,  outline='green', fill='green')
snake_body[0] = root.create_rectangle(960, 576, 1024, 640, outline='green', fill='green')

apple_pos = (0, 576)
apple = root.create_rectangle(apple_pos[0], apple_pos[1], apple_pos[0] + 64, //
apple_pos[1] + 64, outline='red', fill='red')
#apple = root.create_rectangle(0, 0, 64, 64,  outline='red', fill='red')


root.pack()
while True:
    
    tk.update_idletasks()
    tk.update()
    print(dir_snake)
    time.sleep(1/5)

I tried to make the program write the direction variable but the variable doesn't change.

Qwertz
  • 1
  • 3
  • 1
    The `dir_snake` you're changing in each of those functions is a *local variable*, entirely unrelated to the global `dir_snake`. Adding `global dir_snake` to each of the event handler functions would be the simplest fix. – jasonharper Jan 04 '23 at 20:14
  • That worked. Thank you! (I wanted to accept your answer but I didn't found out how) – Qwertz Jan 04 '23 at 20:31

0 Answers0