Home > Back-end >  Move multiple object
Move multiple object

Time:11-04

All,

I am writing a code to move multiple balls in a Tkinter window, I know we can easily do this using oops/classes, but I am wondering if we can do this without classes. My current code kind of works but since I use for loops after every iteration one of the balls disappears. can you suggest what's wrong here? and how can I have multiple objects or balls move in a Tkinter window.

from tkinter import * 
import random
import time

tk = Tk()

WIDTH, HEIGHT = 600, 400
canvas = Canvas(tk, width=WIDTH, height=HEIGHT)
canvas.pack()


colors = ['red','green', 'blue', 'orange','magenta', 'grey', 'pink', 'yellow',
          'dodgerblue','turquoise']


balls = []

for _ in range(10):
    balls.append(canvas.create_oval(random.randrange(1,10),random.randrange(1,10),random.randrange(50,100), random.randrange(50,100), fill = random.choice(colors)))


  
while True:
    
    x = random.randrange(1,5)
    y = random.randrange(1,5)
    
    
    for b in balls:
        canvas.move(b,x,y)
        pos = canvas.coords(b)
        if pos[3] >=HEIGHT or pos[1] <=0:
            y = -y
        if pos[2] >=WIDTH or pos[0] <=0:
            x = -x
       
    tk.update()
    time.sleep(0.03)
            
     
tk.mainloop()

CodePudding user response:

Your code is working. Unfortunately, you didn't mention bouncing balls. The HEIGHT and WIDTH don't help with offset screen. By using winfo_height() and winfo_width() will solve the problem. As for me, I used a bouncing ball using class instantiate module. And canvas.move(b,x,y) is always placed after if/else condition block. The balls will go offset and will return to the screen. The balls will be separated at random.

Here is snippet code:

x = random.randrange(1,55)
y = random.randrange(1,55)
  
while True:    
    for b in balls:
        #canvas.move(b,x,y) 
        pos = canvas.coords(b)
        if pos[3] >=canvas.winfo_height() or pos[1] <=0:
            y = -y
        if pos[2] >=canvas.winfo_width()or pos[0] <=0:
            x = -x
        canvas.move(b,x,y)
    tk.update()
    time.sleep(0.01)

Result:

enter image description here

You can change value from 55 to higher to suit your need.

  • Related