Rastko Jović
Rastko Jović

Reputation: 139

Python tkinter root.after_cancel() issue

up, down, left, right = None, None, None, None

def cancel_movement():
    global up, down, left, right
    try:
        root.after_cancel(up)
        root.after_cancel(down)
        root.after_cancel(left)
        root.after_cancel(right)
    except:
        pass


def move_down(event=None):
    cancel_movement()

    if canvas.coords(snak[-1]) == food_copy:
        canvas.delete(food)
        snak.append(canvas.create_rectangle(food_copy[0], food_copy[1], food_copy[2], food_copy[3], fill="red"))
        create_food()

    prethodna_vrednost = canvas.coords(snak[0])
    prosli = prethodna_vrednost
    canvas.move(snak[0], 0, 10)

    for x in range(1, len(snak)):
         prosli = canvas.coords(snak[x])
         x1 = prethodna_vrednost[0]
         y1 = prethodna_vrednost[1]
         x2 = prethodna_vrednost[2]
         y2 = prethodna_vrednost[3]
         canvas.coords(snak[x], x1, y1, x2, y2)
         prethodna_vrednost = prosli
    check_collision()
    down = root.after(100, move_down)

When i use cancel_movement() nothing seems to happen, what am i doing wrong? Besides the move_down function there are move_up, move_left and move_right functions.

Also is there a better way to prevent calling of the same movement function multiple times besides using the root.after_cancel on every call?

Upvotes: 1

Views: 745

Answers (1)

zondo
zondo

Reputation: 20336

When you say down = root.after(100, move_down), you are defining a local variable. To make it global, add global down to the beginning of your function. The reason this effects you is that if it is a local variable, then the variables you define at the beginning of your program remain None.

>>> x = 4
>>> def func():
...     x = 6
...
>>> print(x)
4
>>> func()
>>> print(x)
4
>>> def globalfunc():
...     global x
...     x = 6
...
>>> print(x)
4
>>> globalfunc()
>>> print(x)
6

Upvotes: 1

Related Questions