[英]Python tkinter Canvas root.after() maximum recursion depth exceeded
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):
canvas.move(rect, 0, 10)
root.after(1, move_down(event))
root.bind('<Down>', move_down)
root.mainloop()
我似乎無法弄清楚如何讓root.after()
工作。 我該如何解決這個問題,以便矩形不斷向下移動?
簡短版本:您不能在傳遞給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
的函數, 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()
(這不一定是最好的方法,但是它演示了基本方法)
我建議不要使用 root.after(),所以當你點擊它時它會移動,而當你停止點擊時它不會移動
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.