简体   繁体   中英

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.

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.

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.

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 
        ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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