0

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!

Timmy
  • 125
  • 1
  • 11
  • The cause of the problem is simply: you're moving the bubbles as fast as you possibly can. Every iteration of that infinite loop only takes a handful of milliseconds. – Bryan Oakley Jun 30 '18 at 19:13

2 Answers2

1

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.

1

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)
Attersson
  • 4,755
  • 1
  • 15
  • 29