1 回答
TA贡献1860条经验 获得超8个赞
您可以循环创建多个项目。将项目 ID 保存在列表中,然后您可以迭代这些项目来移动它们。
下面的示例在随机位置创建 100 个具有随机颜色的项目,然后为它们在每次迭代中以随机数量下落设置动画。
import tkinter as tk
import random
root = tk.Tk()
canvas = tk.Canvas(root, bg="black", width=400, height=400)
canvas.pack(fill="both", expand=True)
items = []
for i in range(100):
x = random.randint(10, 490)
y = random.randint(10, 490)
size = random.randint(20,50)
color = random.choice(("red", "orange", "green", "blue", "white", "yellow"))
item_id = canvas.create_rectangle(x, y, x+size, y+size, fill=color, outline="white")
items.append(item_id)
def animate():
for item_id in items:
distance = random.randint(0, 5)
canvas.move(item_id, 0, distance)
canvas.after(100, animate)
animate()
root.mainloop()
这是一种面向对象的方法,我们使用类来定义项目,并且类实例可以为自身设置动画。
import tkinter as tk
import random
class RandomItem:
def __init__(self, canvas):
self.canvas = canvas
self.velocity = random.randint(1,5)
x = random.randint(10, 490)
y = random.randint(10, 490)
size = random.randint(20,50)
color = random.choice(("red", "orange", "green", "blue", "white", "yellow"))
self.item_id = canvas.create_rectangle(x, y, x+size, y+size, fill=color)
self.fall()
def fall(self):
self.canvas.move(self.item_id, 0, self.velocity)
self.canvas.after(100, self.fall)
root = tk.Tk()
canvas = tk.Canvas(root, bg="black", width=500, height=500)
canvas.pack(fill="both", expand=True)
for i in range(100):
item = RandomItem(canvas)
root.mainloop()
添加回答
举报