我在这里遇到的问题是我无法找到某种类型的最近对象。最好我给你代码,让你明白我的意思:
from Tkinter import *
root = Tk()
f=Frame(root)
f.grid()
w=Canvas(f)
def identify(event): ## this should identify the tag near to click
item = w.find_closest(event.x, event.y)[0]
print item
line1=w.create_line(50,50,150,150, width=5, tags="line")
line2=w.create_line(100,100,100,350, width=3, tags="line")
line3=w.create_line(150,150,150,450, width=3, tags = "line")
w.grid(row=0, column=0)
w.bind("<ButtonRelease-1>", identify)
u=Frame(f)
u.grid(row=0, column=1)
root.mainloop()
正如您在此处看到的,您可以单击屏幕上的任意位置,它将返回最近的对象。这是我想要实现的,但在屏幕上有其他我希望被忽略的对象。我可以通过使用标签来做到这一点,但这里的问题是您出于某种原因需要单击实际对象。此代码用于显示我的问题。我的实际代码是河内塔游戏,我的目标是找到最近的极点,以便磁盘能够捕捉到它,但是如果在移动磁盘之前不单击每个极点,我就无法找到最近的极点。
这是显示我的问题的代码。注意:我只将 "w.bind("", identify)" 更改为 "w.tag_bind("line", "", identify)"
from Tkinter import *
root = Tk()
f=Frame(root)
f.grid()
w=Canvas(f)
def identify(event): ## this should identify the tag near to click
item = w.find_closest(event.x, event.y)[0]
print item
line1=w.create_line(50,50,150,150, width=5, tags="line")
line2=w.create_line(100,100,100,350, width=3, tags="line")
line3=w.create_line(150,150,150,450, width=3, tags = "line")
w.grid(row=0, column=0)
w.tag_bind("line", "<ButtonRelease-1>", identify)
u=Frame(f)
u.grid(row=0, column=1)
root.mainloop()