短版本:您不能在您傳遞給after
的功能上放置括號。
root.after(1,move_down(event))
此行不註冊該功能move_down
爲after
事件的回調。相反,它立即調用move_down
,並且如果未輸入無限遞歸,則會將返回值move_down
註冊爲回調。
要解決這個問題,只需使用move_down
而不實際調用它,並且使event
爲可選變量,因爲after
不會提供值。您應該也可以使用大於1毫秒的時間,否則您的矩形將在一眨眼之間拉開屏幕。
from tkinter import *
root = Tk()
canvas = Canvas(root, width=400, height= 400, bg="white")
canvas.pack()
rect = canvas.create_rectangle(100, 100, 110, 110, fill='blue')
def move_down(event=None):
canvas.move(rect, 0, 10)
root.after(100,move_down)
root.bind('<Enter>', move_down) #or whatever you're binding it to
root.mainloop()
獎金信息:如果你要問「好了,現在我怎麼矩形停止移動時,我鬆開按鍵,如何使彼此的方向移動?當我按下其他箭頭鍵?「這需要更復雜的設計。您需要註冊到root.after
的函數根據矩形的速度移動可變數量的像素,並根據獨立發生的關鍵事件改變矩形的速度。示例實現:
from tkinter import *
root = Tk()
canvas = Canvas(root, width=400, height= 400, bg="white")
canvas.pack()
rect = canvas.create_rectangle(100, 100, 110, 110, fill='blue')
x_velocity = 0
y_velocity = 0
keys_being_held_down = set()
key_accelerations = {
"Up": (0, -10),
"Down": (0, 10),
"Left": (-10, 0),
"Right": (10, 0)
}
def key_pressed(event):
global x_velocity, y_velocity
#ignore autorepeat events
if event.keysym in keys_being_held_down:
return
keys_being_held_down.add(event.keysym)
acceleration = key_accelerations[event.keysym]
x_velocity += acceleration[0]
y_velocity += acceleration[1]
def key_released(event):
global x_velocity, y_velocity
keys_being_held_down.remove(event.keysym)
acceleration = key_accelerations[event.keysym]
x_velocity -= acceleration[0]
y_velocity -= acceleration[1]
def tick():
canvas.move(rect, x_velocity, y_velocity)
print(x_velocity, y_velocity)
root.after(100,tick)
for key in key_accelerations:
root.bind("<{}>".format(key), key_pressed)
root.bind("<KeyRelease-{}>".format(key), key_released)
root.after(100, tick)
root.mainloop()
(這是不是一定要做到這一點的最好辦法,但它表明了基本方法)