2017-11-17 4 views
1

파이썬 tkinter에서이 프로그램을 만들려고했습니다. 공이 화면에 나타나고 클릭 할 때마다 공이 내가 클릭 한 지점까지 미끄러지기를 원합니다. 볼의 x 및 y 위치는 변경되었지만 볼의 "이동"이 완료된 후에 만 ​​다시 그립니다. 누군가 내가 뭘 잘못하고 있는지 말할 수 있습니까? 당신이 공의 중간 위치가 표시되지 않는 이유는 전체 GUI를 일시 정지 time.sleep 코드에서파이썬 tkinter에서 볼을 어떻게 활주시킬 수 있습니까?

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() 
+0

캔버스를 그리면 업데이트 할 것인지 묻지 않는 것처럼 보입니다. –

답변

0

, 즉이다. 대신 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") 
관련 문제