我正试图用我的球创造一个“更平滑”的运动。基本上,我希望我的程序能够检测按键的时间,让它以恒定的速度移动球,并且当没有按下按键时,让它停止。
这是我的代码:
import time
import Tkinter
import math
root = Tkinter.Tk()
r = 10
x = 150
y = 150
canvas = Tkinter.Canvas(root, width=600, height=600, background='#FFFFFF')
canvas.grid(row=0, rowspan=2, column=1)
circle_item = canvas.create_oval(x - r, y - r, x + r, y + r,
outline='#000000', fill='#00FFFF')
global leftInt
leftInt = 0
def leftMove(Event):
global leftInt
leftInt = 1
gogo = 1
if (gogo == 1):
ballMove()
gogo = 2
def leftStop(Event):
global leftInt
leftInt = 0
print("im stop")
def rightMove(Event):
canvas.move(circle_item, 5, 0)
x1, y1, x2, y2 = canvas.coords(circle_item)
def upMove(Event):
canvas.move(circle_item, 0, -5)
x1, y1, x2, y2 = canvas.coords(circle_item)
def downMove(Event):
canvas.move(circle_item, 0, 5)
x1, y1, x2, y2 = canvas.coords(circle_item)
def ballMove():
global leftInt
while (leftInt == 1):
print('im go')
canvas.move(circle_item, -5, 0)
x1, y1, x2, y2 = canvas.coords(circle_item)
time.sleep(.1)
ballMove()
root.bind('<Left>', leftMove)
root.bind('<KeyRelease>', leftStop)
root.bind('<Right>', rightMove)
root.bind('<Up>', upMove)
root.bind('<Down>', downMove)
root.mainloop()
我试图在按下时创建一个while循环,然后让KeyRelease停止它。为什么不停止?我该如何解决这个问题?