在python tkinter中如何让球滑行?

2024-09-19 23:40:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个我试图用pythonttkinter制作的程序。屏幕上会出现一个球,每次我点击时我都希望球滑到我点击的点。球的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()

Tags: importeventtimedefcreaterootwidthcanvas
1条回答
网友
1楼 · 发布于 2024-09-19 23:40:15

在您的代码中,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")

相关问题 更多 >