mercredi 29 juin 2016

Does canvas.bind work in a while loop


I have a program in Python 3.4.4 using Tkinter, that is supposed to move a square around the screen.

Unfortunately, canvas.bind doesn't seem to be working while inside a while loop, but it needs to be inside of the while loop or else the square won't move. This is because I'm technically drawing a new square with different x, y, x1, and y1 coordinates each time the loop runs, and the bind is what makes the square move in each direction according to the arrow keys.

So here's the code:

from tkinter import *
import time, random
tk = Tk()
canvas = Canvas(tk, width = 1000, height = 1000)
canvas.pack()

def move(event):
    if event.keysym == 'Up':
        y-=10
        y1-=10
    elif event.keysym == 'Down':
        y+=10
        y1+=10
    elif event.keysym == 'Right':
        x+=10
        x1+=10
    elif event.keysym == 'Left':
        x+=10
        x1+=10


background = canvas.create_rectangle(0, 0, 1000, 1000, fill = 'orange') #draws background
ranNum=random.random()*960  #Creates a random number
ranNum1=random.random()*960 #Creates a random number
food = canvas.create_rectangle(ranNum, ranNum1, ranNum + 15, ranNum1 + 15, fill='green') #creates food
r1 = None
o = 0
length = 4
x = 500
y = 500
x1 = 515
y1 = 515
while o < length:          
    if canvas.find_overlapping(ranNum, ranNum, ranNum + 15, ranNum1 + 15) == True:
        x+=5
        y+=5
        x1+=5
        y1+=5
        canvas.delete(food)
    r=canvas.create_rectangle(x, y, x1, y1, fill = 'blue')
    canvas.bind('<KeyPress-Up>', move )
    canvas.bind('<KeyPress-Down>', move)
    canvas.bind('<KeyPress-Left>', move)
    canvas.bind('<KeyPress-Right>', move)
    time.sleep(.0)
    canvas.delete(r1)
    tk.update()
    r1 = r

Aucun commentaire:

Enregistrer un commentaire