我想使三个随机生成的圆的运动更平滑。有人可以帮我吗?预先谢谢您:)这是我当前的代码:
import tkinter
from time import sleep
from random import randrange
class Circle:
def __init__(self, color):
a = randrange(250)
b = randrange(250)
self.color = color
self.id = canvas.create_oval(a,b,a+40,b+40, fill=self.color)
def move(self):
canvas.move(self.id, 5,15)
window = tkinter.Tk()
window.geometry("500x400")
canvas = tkinter.Canvas(width=400, height=300)
canvas.pack()
circle1 = Circle('red')
circle2 = Circle('yellow')
circle3 = Circle('blue')
while(3):
canvas.update()
sleep(1)
circle1.move()
circle2.move()
circle3.move()
window.mainloop()
答案 0 :(得分:1)
使用tkinter.after
代替sleep
,并让mainloop代替while loop
和canvas.update()
来执行其工作。
类似这样的东西:
import tkinter
from random import randrange
class Circle:
def __init__(self, color):
a = randrange(250)
b = randrange(250)
self.color = color
self.id = canvas.create_oval(a,b,a+40,b+40, fill=self.color)
def move(self):
canvas.move(self.id, 1, 1)
def move_circles(circles):
for circle in circles:
circle.move()
window.after(10, move_circles, circles)
window = tkinter.Tk()
window.geometry("500x400")
canvas = tkinter.Canvas(width=400, height=300)
canvas.pack(expand=True, fill=tkinter.BOTH)
circle1 = Circle('red')
circle2 = Circle('yellow')
circle3 = Circle('blue')
circles = [circle1, circle2, circle3]
move_circles(circles)
window.mainloop()