python - 如何让圆圈的运动更加流畅?

标签 python python-3.x canvas tkinter tkinter-canvas

我想让三个随机生成的圆圈的运动更加平滑。有人能帮我吗?预先感谢您:)这是我当前的代码:

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 loopcanvas.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()

关于python - 如何让圆圈的运动更加流畅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57590563/

相关文章:

javascript - 在 <img> 标签中显示 Canvas 图像的一部分

javascript - Chartjs v2 xAxes 标签与 scaleLabel 重叠

python - 为什么 Python 中的连接看起来越来越慢?

Python 创建 C 线程

python - 如何从具有时间戳范围的 pandas 对象获取不同的组

python - 在 virtualenv 中使用 Python 3

python - 多处理模块中 Pool 对象和 Manager 对象之间的位置

python - 我如何在 IntervalIndex 中获得一些值(value)?

python - 如何在 Python 中退出循环?

android - Canvas.drawText(...) 不打印换行符