Reputation: 3
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
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