如何让圆圈的运动更顺畅?
How to make the movement of the circles smoother?
我想让随机生成的三个圆圈的移动更流畅。任何人都可以帮我吗?提前谢谢你 :) 这是我当前的代码:
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()
使用tkinter.after
代替sleep
,让主循环完成它的工作,而不是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()
我想让随机生成的三个圆圈的移动更流畅。任何人都可以帮我吗?提前谢谢你 :) 这是我当前的代码:
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()
使用tkinter.after
代替sleep
,让主循环完成它的工作,而不是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()