Daniel Domingos
Daniel Domingos

Reputation: 63

How do I move multiple objects at once on a Tkinter canvas?

I have this code, which moves one of the two Tkinter Canvas objects. How do I make it move both at the same time using canvas.move()?

canvas.create_oval(100, 105, 150, 150, fill = 'light blue', outline = 'green')
canvas.create_oval(200, 205, 150, 150, fill = 'light blue', outline = 'green')

tkinter.update()

for x in range (1, 100):
    canvas.move(1, 5, 0)
    tkinter.update()
    time.sleep(0.05)

Upvotes: 1

Views: 3043

Answers (1)

cdlane
cdlane

Reputation: 41895

This sounds like a job for tags. You can tag your two objects similarly and then ask the canvas to move all objects tagged that way:

import tkinter as tk
import time

root = tk.Tk()

canvas = tk.Canvas(root)
canvas.pack()

canvas.create_oval(100, 105, 150, 150, tags="Bob", fill='light blue', outline='green')
canvas.create_oval(200, 205, 150, 150, tags="Bob", fill='light blue', outline='green')

for _ in range(50):
    canvas.move("Bob", 5, 0)
    canvas.update()
    time.sleep(0.05)

root.mainloop()

Upvotes: 3

Related Questions