【问题标题】:How to make the movement of the circles smoother?如何使圆圈的运动更顺畅?
【发布时间】:2019-08-21 11:25:06
【问题描述】:

我想让三个随机生成的圆圈的运动更平滑。任何人都可以帮助我吗?提前谢谢你:) 这是我当前的代码:

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

【问题讨论】:

  • 你说的更平滑,是不是也意味着他们可以更快地遍历画布?
  • 不要使用 sleep(1),降低这个量会更顺畅
  • 不,他们应该在相同的温度下穿过画布,但不要那么波涛汹涌:) @temp123
  • 如果你将 sleep(1) 的数量除以 10 例如 (0.1) 并使用 canvas.move(self.id, 0.5,1.5) 执行相同的操作,速度将相同,但运动会顺畅十倍(每秒多运动 10 倍)

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


【解决方案1】:

使用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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多