1

我在这里遇到的问题是我无法找到某种类型的最近对象。最好我给你代码,让你明白我的意思:

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()
4

1 回答 1

0

对你来说有点晚了,但也许对其他人有用......

我今天刚遇到同样的问题,并使用第二个 Canvas 解决了这个问题,其中包含所需项目的副本。
这幅画布从未印刷过。这有点棘手,但我找不到更好的。

draft = Canvas(w) # if w is deleted, the draft is deleted


draft.delete(ALL) # if you use the fake canvas for other uses

concerned = w.find_withtag("line") # what you want

for obj in concerned: # copy on draft

    # first, get the method to use
    if w.type(obj) == "line": create = draft.create_line
    # use "elif ..." to copy more types of objects
    else: continue

    # copy the element with its attributes
    config = {opt:w.itemcget(obj, opt) for opt in w.itemconfig(obj)}
    config["tags"] = str(obj) # I can retrieve the ID in "w" later with this trick
    create(*w.coords(obj), **config)

# use coordinates relative to the canvas
x = w.canvasx(event.x)
y = w.canvasy(event.y)

item = draft.find_closest(x,y) # ID in draft (as a tuple of len 1)
if item: item = int( draft.gettags(*item)[0] ) # ID in w
else: item = None # closest not found

print(item)

我希望我可以使用create(*w.coords(obj), **w.itemconfig(obj)),但itemconfig没有参数返回一个其值不能被重用的字典。

关于项目副本:https ://stackoverflow.com/a/20278179/7420421

顺便说一句,我用的是python 3,我不知道它是否适用于python 2。

于 2017-03-20T04:18:53.037 回答