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

时间:2019-03-30 13:36:22

标签: python tkinter tkinter-canvas

我开始使用TKinter,我尝试制作多个弹力球作为训练。当我创建一个唯一的椭圆并使其移动时,一切正常,但是当我创建一个带有move方法的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)

我坚信它会得到相同的结果,但是在第一种情况下,球移动了,而在第二种情况下,球没有移动,我不知道为什么。

1 个答案:

答案 0 :(得分:1)

在您的代码中,canvas.create_oval()函数返回一个对象,然后可以将它移动到名为canvas.move(object, ...)的函数中。但是正如您所看到的,您正在类方法self中传递move

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

这是您通过执行ball1定义(实际上是重新分配)的Ball类的实例,在本例中为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.

的内容
相关问题