简体   繁体   English

tkinter:通过单击移动图像

[英]tkinter: moving an image by clicking

I'm trying to create a function that allows you to select an image on a Canvas by clicking on it, then with the same mouse button, click on the Canvas to teleport this image to the coordinates of the second click. I'm trying to create a function that allows you to select an image on a Canvas by clicking on it, then with the same mouse button, click on the Canvas to teleport this image to the coordinates of the second click.

Currently I know how to select the image using find_closest , move it with coords but I don't know how to write the code.目前我知道如何使用find_closest select 图像,用coords移动它,但我不知道如何编写代码。

for now I have:现在我有:

self.cnv.bind('<Button-1>', self.select)
def select(self, event):
    self.item = self.cnv.find_closest(event.x, event.y)
    self.cnv.coords(self.item, event.x, event.y)

but it just moves the image directly when I click on it, whereas I would like to select it first and then move it with a second click.但是当我单击它时它只是直接移动图像,而我想先 select 它然后再单击移动它。

The way I might do this is to first check to see if any items have the tag "selected" when you detect a click.我可能会这样做的方法是首先检查当您检测到点击时是否有任何项目具有“已选择”标签。 If there are one or more items with the "selected" tag, move them.如果有一个或多个带有“选定”标签的项目,请移动它们。 If there are none with the "selected" tag, then add the tag to the nearest item.如果没有带有“选定”标签的标签,则将标签添加到最近的项目。

The logic would look something like this:逻辑看起来像这样:

def handle_click(event):
    canvas = event.widget
    items = canvas.find_withtag("selected")
    if items:
        # move the items to the new coordinates
        ...
   else:
        # add the 'select' tag to the item closest
        # to the click 
        ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM