我在尝试使用 TKinter 移动椭圆时遇到问题

I have trouble trying to move an oval with TKinter

我开始使用 TKinter 并尝试制作多个弹跳球作为训练练习。当我创建一个独特的椭圆并使其移动时,一切正常,但是当我创建一个带有移动方法的 Ball class 时,球根本不会移动。我没有收到任何错误消息,但它拒绝移动。

"""
Initialisation
"""
from tkinter import *
import time

w_height    = 600
w_width     = 800
xspeed      = 10
yspeed      = 10

window = Tk()
window.geometry ("{}x{}".format(w_width, w_height))
window.title("Bouncing Balls")
canvas = Canvas(window, width = w_width - 50,height = w_height - 50, bg="black")


"""
If i create the ball like that and make it move it works fine
"""

ball1 = canvas.create_oval(10, 10, 50, 50, fill ="red")
while True:
    canvas.move(ball1, xspeed, yspeed)
    window.update()
    time.sleep(0.05)
"""
But if i try to create the ball using a class it doesn't work anymore...
"""

class Ball:
    def __init__(self, posx, posy, r):
        canvas.create_oval(posx-r, posy-r, posx+r, posy+r, fill ="red")

    def move(self, dx, dy):
        canvas.move(self, dx, dy)

ball1 = Ball(50,50,10)

while True:
    ball1.move(xspeed, yspeed)
    window.update()
    time.sleep(0.05)

我认为它会给出相同的结果,但在第一种情况下,球会移动,而在第二种情况下,它不会移动,我不明白为什么。

在您的代码中,canvas.create_oval() 函数 returns 一个对象,然后可以将其移动到我调用的 canvas.move(object, ...) 函数中。但是正如您所看到的,您在 class 方法 move.

中传递了 self
def move(self, dx, dy):
    canvas.move(*self*, dx, dy)

这是 class 球的实例,在本例中为 ball1 变量,您通过 ball1 = Ball(50, 50, 10).

定义(实际上重新分配)

要使此工作正常进行,请将您的 class 更改为此。

class Ball:

    def __init__(self, posx, posy, r):
        self.ball = canvas.create_oval(posx-r, posy-r, posx+r, posy+r, fill ="red")

    def move(self, dx, dy):
        canvas.move(self.ball, dx, dy)

Here you define a class field that will get what returns canvas.create_oval() function and then use it to move the object.