如何让球在python tkinter中滑行?

时间:2017-11-17 18:26:15

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

我有这个程序,我试图在python tkinter。一个球将出现在屏幕上,每次我点击我想让球滑到我点击的点。球的x和y位置发生了变化,但球只在球完成“移动”后重新绘制。有人能告诉我我做错了什么。

from tkinter import *
import time
width = 1280
height = 700
ballRadius = 10
iterations = 100
mouseLocation = [width/2, height/2]
ballLocation = [width/2, height/2]

root = Tk()

def drawBall(x, y):
    canvas.delete(ALL)
    canvas.create_oval(x - ballRadius, y - ballRadius, x + ballRadius, y + ballRadius, fill="blue")
    print(x, y)

def getBallLocation(event):
    mouseLocation[0] = event.x
    mouseLocation[1] = event.y
    dx = (ballLocation[0] - mouseLocation[0]) / iterations
    dy = (ballLocation[1] - mouseLocation[1]) / iterations
    for i in range(iterations):
        ballLocation[0] -= dx
        ballLocation[1] -= dy
        drawBall(round(ballLocation[0]), round(ballLocation[1]))
        time.sleep(0.02)
    ballLocation[0] = event.x
    ballLocation[1] = event.y

canvas = Canvas(root, width=width, height=height, bg="black")
canvas.pack()
canvas.create_oval(width/2-ballRadius, height/2-ballRadius, width/2+ballRadius, height/2+ballRadius, fill="blue")
canvas.bind("<Button-1>", getBallLocation)

root.mainloop()

1 个答案:

答案 0 :(得分:0)

在您的代码中time.sleep暂停整个GUI,这就是您没有看到球的中间位置的原因。相反,您可以使用widget.after方法构造函数。请尝试以下方法:

    print(x, y)


dx = 0
dy = 0
def getBallLocation(event):
    canvas.unbind("<Button-1>")
    global dx, dy
    mouseLocation[0] = event.x
    mouseLocation[1] = event.y
    dx = (ballLocation[0] - mouseLocation[0]) / iterations
    dy = (ballLocation[1] - mouseLocation[1]) / iterations
    draw()

i = 0
def draw():
    global i
    ballLocation[0] -= dx
    ballLocation[1] -= dy
    drawBall(round(ballLocation[0]), round(ballLocation[1]))
    if i < iterations-1:
        canvas.after(20, draw)
        i += 1
    else:
        canvas.bind("<Button-1>", getBallLocation)
        i = 0

canvas = Canvas(root, width=width, height=height, bg="black")