juiceboxes
juiceboxes

Reputation: 13

Copy Tkinter Canvas Items

I need top be able to create a copy of a tkinter canvas item, so that a copy of an image can be dragged off of an original. I have dragging working for the images, but I cannot seem to copy the image item. Any help would be greatly appreciated! Thanks.

EDIT: Sorry for not including my code at first. I was able to solve the problem thanks to the answer that was given. Here's a trimmed down example of my code that now works:

from tkinter import *
from PIL import Image, ImageTk

def OnBaseButtonPress(event):
    #record the item and its location
    drag_data["item"] = c.find_closest(event.x, event.y)

    i = c.itemcget(drag_data["item"], "image") #finds the image source of the object
    refs.append(i) #keep a reference!
    c.create_image(c.coords(drag_data["item"]), image=i, tags="base") #creates an identical object at the position

    drag_data["x"] = event.x
    drag_data["y"] = event.y

def OnBaseButtonRelease(event):
    #reset drag info
    drag_data["item"] = None
    drag_data["x"] = 0
    drag_data["y"] = 0

def OnBaseMotion(event):
    #calculate how far the item has moved
    delta_x = event.x - drag_data["x"]
    delta_y = event.y - drag_data["y"]
    #move the object that amount
    c.move(drag_data["item"], delta_x, delta_y)
    #record the new position
    drag_data["x"] = event.x
    drag_data["y"] = event.y

#set up canvas and image
root = Tk()
c = Canvas(root, width=800, height=600)
c.pack()
test = ImageTk.PhotoImage(Image.open("test.png"))
c.create_image(400, 300, image=test, tags="base")
refs=[] #used to keep references to images used in functions

#bind mouse keys 
c.tag_bind("base", "<ButtonPress-1>", OnBaseButtonPress)
c.tag_bind("base", "<ButtonRelease-1>", OnBaseButtonRelease)
c.tag_bind("base", "<B1-Motion>", OnBaseMotion)

drag_data={"x": 0, "y": 0, "item": None}

mainloop()

Upvotes: 1

Views: 4460

Answers (1)

furas
furas

Reputation: 142641

You can get item type canvas.type(item), item configuration canvas.itemconfig(item), and etc.

And then you can recreate an identical object.

See also: Tkinter - making a second canvas display the contents of another.

Upvotes: 3

Related Questions