python tkinter tag_bind不在循环内部工作

时间:2016-06-02 05:22:24

标签: python-3.x tkinter tkinter-canvas

from tkinter import *

def onObjectClick(event, obj):
    canv.itemconfig(obj, width=2)

def no_onObjectClick(event, obj):
    canv.itemconfig(obj, width=1)    

root = Tk()
canv = Canvas(root, width=500, height=500)

can_obj = []

w=10
ii=0
while ii < 2:
    points = [w,100, w+10,0, w+20,100]
    ln = canv.create_line(points, fill='green')
    can_obj.append(ln)
    w+=10
    ii+=1
ii=0

##this part is working fine
##canv.tag_bind(can_obj[1], '<Enter>', lambda event : onObjectClick(event, can_obj[1]))
##canv.tag_bind(can_obj[1], '<Leave>', lambda event : no_onObjectClick(event, can_obj[1]))
##canv.tag_bind(can_obj[0], '<Enter>', lambda event : onObjectClick(event, can_obj[0]))
##canv.tag_bind(can_obj[0], '<Leave>', lambda event : no_onObjectClick(event, can_obj[0]))


#this is not working as above
for obj in can_obj:
    canv.tag_bind(obj, '<Enter>', lambda event : onObjectClick(event, obj))
    canv.tag_bind(obj, '<Leave>', lambda event : no_onObjectClick(event, obj))


canv.pack()
#root.mainloop()

在Windows上使用python 3.4,它在使用循环时仅突出显示最后一个对象。但手动(没有循环其正常工作,如评论部分中所用)...任何解决方案??

1 个答案:

答案 0 :(得分:2)

当你在for循环中执行此操作时,lambda会捕获最后一个读取对象的最后一个 ID 。作为证明,如果以相反的顺序(popBackStack())遍历对象列表,您将注意到只有最左边的对象按预期运行。

您可以使用辅助函数解决问题:

for obj in reversed(can_obj):

演示

使用上面的代码将引导您获得您期望的结果:

  1. 将鼠标悬停在第二个对象上: enter image description here

  2. 将鼠标移动到第一个对象: enter image description here