我尝试使用 TKinter 移动椭圆时遇到麻烦



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

"""
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()函数返回一个对象,然后可以移动我调用的canvas.move(object, ...)函数。但如您所见,您正在类方法中传递selfmove.

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

这是类 Ball 的实例,在本例中ball1变量,您通过执行ball1 = Ball(50, 50, 10)定义(实际重新分配)。

要使此操作,请将您的类更改为此。

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)

在这里,您定义一个类字段,该字段将获取返回canvas.create_oval() function and then use it to move the object.

最新更新