[英]TKinter: Move while key is pressed, stopped when not
我試圖用我的球進行“順滑”運動。 基本上,我希望我的程序檢測何時按下某個鍵,並使它以恆定的速度移動球,而當未按下該鍵時,則使其停止。
這是我的代碼:
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停止它。 為什么不停止? 我怎樣才能解決這個問題?
請注意,操作系統的重復頻率以及如何處理按下的鍵決定了會發生什么,因此即使您連續按下該鍵,您也可能同時看到“ im go”和“ im stop”。 更改ballMove()以使用Tkinter的after方法。 您不應在GUI程序中使用time.sleep(),因為它可能會中斷GUI的無限循環。
def ballMove():
global leftInt
if (leftInt == 1):
x1, y1, x2, y2 = canvas.coords(circle_item)
print('im go', x1)
if x1 > 3: ## keep it on the canvas
canvas.move(circle_item, -5, 0)
root.after(100, ballMove)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.