Loïc Caparroy
Loïc Caparroy

Reputation: 3

'Move object' function bound to a key in Tkinter can only make one object move at a time, how to make more object move at the same time?

I've bound a key to a function which makes an oval (included in a list of other identical ovals) moves a certain distance. I want it to make a new oval moves each time I press the key, without stopping the previous moving oval if its course is not over.

With my code, by pressing 'c', I create a new oval randomly placed on the canvas, and saved in a dictionary. Each new oval is saved with key = 'compteur', 'compteur' increments for every new oval created to make sure every oval is not created over a previous existing one. By pressing 'm', I want to make a new oval move each time I press the key, without the previous one stopping.

from tkinter import *
import time
from random import *
import time

compteur = 0
dic = {}

w = Tk()
w.geometry('400x400')

c = Canvas(w, width = 400, height = 400)
c.pack()

dic[compteur] = c.create_oval(200,150,250,200,fill = 'pink')
compteur += 1

def create(event):

    global compteur
    b = randrange(300)
    dic[compteur] = c.create_oval(200,b,250,(b+50),fill = 'pink')
    compteur += 1

def move(event):

    rond = dic[randrange(len(dico))]

    if c.coords(rond)[0] == 200:

        for x in range (15):

            c.move(rond,-10,0)
            w.update()
            time.sleep(0.15)         

w.bind('<m>', move)
w.bind('<c>',create)
w.mainloop()

I'm obviously missing something but as I'm a beginner, I have no idea why only one oval can move at a time. And weirdly, once the second oval finish it's course, the first one starts again to finish its course too.

Thanks for your help :)

Upvotes: 0

Views: 71

Answers (1)

furas
furas

Reputation: 142804

I use list to keep all circles.

In move() I move last circle from list only when I press <m>

In move_other() I move all circles except last one and use after() to run move_other() after 100ms (0.1s) so it will move all time.

from tkinter import *
from random import *

# --- fucntions ---

def create(event):
    b = randrange(300)
    circles.append(c.create_oval(200, b, 250, (b+50), fill='pink'))

def move(event):
    item = circles[-1]
    c.move(item, -10, 0)

def move_other():
    for item in circles[:-1]:
        c.move(item, -10, 0)

    w.after(100, move_other)

# --- main ---

circles = []

w = Tk()
w.geometry('400x400')

c = Canvas(w, width=400, height=400)
c.pack()

circles.append(c.create_oval(200, 150, 250, 200, fill='pink'))

move_other() # start moving other circles

w.bind('<m>', move)
w.bind('<c>', create)

w.mainloop()

Upvotes: 1

Related Questions