Reputation: 125
I've made this code to create bubbles which move from the right side to the left side of the screen in tkinter:
from tkinter import *
window = Tk()
c = Canvas(window, width=800, height=500, bg="darkblue")
c.pack()
list1 = list()
speedlist = list()
from random import randint
def create_bubble():
id1 = c.create_oval(randint(50, 70), randint(210, 240), randint(910, 930), randint(240, 260), outline="white")
list1.append(id1)
speedlist.append(randint(1, 10))
def move_bubbles():
for i in range(len(list1)):
c.move(list1[i], -speedlist[i], 0)
while True:
if randint(1, 10) == 1:
create_bubble()
move_bubbles()
window.update()
They move very well but as fast as some mice being chased by a cat. You almost cannot see them. Of course I can set the speed between small numbers but that would be silly and I want to know the cause of the problem. Can anybody help me? Thanks!
Upvotes: 0
Views: 730
Reputation: 4866
The loop currently in place calls the move_bubbles()
function a non-deterministic amount of times per second.
It would be correct to tie every movement to how much time has elapsed from one execution of the function to another and use a speed coefficient:
import time
t1=time.time()
speed=0.2 #tweak it
#...
def move_bubbles():
delta_time=time.time()-t1
t1=time.time()
for i in range(len(list1)):
c.move(list1[i], delta_time*speed*-speedlist[i], 0)
Upvotes: 1
Reputation:
You can just reduce the speed of the bubbles replacing
speedlist.append(randint(1, 10))
By:
ratio = 0.1
speedlist.append(randint(1, 10) * ratio)
Bubbles will be 10 times slower.
Upvotes: 1