canvas 圈子在 python 中变形

canvas circle getting distorted in python

我正在编写代码,其中在 Tkinter 中有多个不同大小的球(或圆圈)canvas。问题是,在 运行 过程中,当球接近 canvas 边界,有时甚至远离边界时,球的形状就会变形。我不确定为什么会这样。 window 对象更新期间我遗漏了什么吗?

这是主文件:

from tkinter import *
from Ball import *
import time


HEIGHT = 500
WIDTH = 500


window = Tk()
canvas = Canvas(window, height=HEIGHT, width=WIDTH)
canvas.pack()

volley_ball = Ball(canvas, 0, 0, 100, 2, 2,'red')
cricket_ball = Ball(canvas, 10, 10, 30, 4, 2,'green')
golf_ball =  Ball(canvas, 100, 100, 20, 8, 6,'white')


while True:
    volley_ball.move()
    cricket_ball.move()
    golf_ball.move()

    window.update()
    time.sleep(0.01)

window.mainloop()

这是球class模块代码:

class Ball:

    def __init__(self, canvas, x, y, diameter, xVelocity, yVelocity, color):
        self.canvas = canvas
        self.image = canvas.create_oval(x, y, diameter, diameter, fill=color)
        self.xVelocity = xVelocity
        self.yVelocity = yVelocity
        self.diameter = diameter

    def move(self):
        self.coordinates = self.canvas.coords(self.image)
        if(self.coordinates[2] >= self.canvas.winfo_width() or self.coordinates[0] < 0):
            self.xVelocity = -self.xVelocity
        if (self.coordinates[3] >= self.canvas.winfo_height() or self.coordinates[1] < 0):
            self.yVelocity = -self.yVelocity
        self.canvas.move(self.image, self.xVelocity, self.yVelocity)

视觉效果是通过过度驱动您的 move 功能而产生的。尝试将延迟更改为 1 毫秒并观察伪影!放慢一点,用xVelocity,yVelocity来控制速度。

也可以尝试将 while 循环更改为 window.after

def animate():
    volley_ball.move()
    cricket_ball.move()
    golf_ball.move()
    window.after(20, animate)

window.after(500, animate)
window.mainloop()