[英]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
,讓 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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.