Python 复制Tkinter画布项目

Python 复制Tkinter画布项目,python,tkinter,Python,Tkinter,我需要能够创建一个tkinter画布项目的副本,这样一个图像的副本可以从原始文件中拖出。我对图像进行了拖动,但似乎无法复制图像项。任何帮助都将不胜感激!谢谢 编辑:很抱歉没有包括我的代码在第一。多亏了给出的答案,我才能够解决这个问题。下面是我的代码的一个精简示例,它现在可以工作了: from tkinter import * from PIL import Image, ImageTk def OnBaseButtonPress(event): #record the item and

我需要能够创建一个tkinter画布项目的副本,这样一个图像的副本可以从原始文件中拖出。我对图像进行了拖动,但似乎无法复制图像项。任何帮助都将不胜感激!谢谢

编辑:很抱歉没有包括我的代码在第一。多亏了给出的答案,我才能够解决这个问题。下面是我的代码的一个精简示例,它现在可以工作了:

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()
从tkinter导入*
从PIL导入图像,ImageTk
def OnBaseButton按(事件):
#记录项目及其位置
拖动_数据[“项”]=c.find_最接近(event.x,event.y)
i=c.itemcget(拖动数据[“item”],“image”)#查找对象的图像源
参考文献。附加(i)#保留参考文献!
c、 创建图像(c.coords(拖动数据[“项]),image=i,tags=“base”)#在该位置创建相同的对象
拖动数据[“x”]=event.x
拖动数据[“y”]=event.y
def OnBaseButtonRelease(事件):
#重置拖动信息
拖拽数据[“项目”]=无
拖拽数据[“x”]=0
拖动数据[“y”]=0
def OnBaseMotion(事件):
#计算项目移动的距离
delta_x=event.x-拖动_数据[“x”]
delta_y=event.y-拖动数据[“y”]
#移动该数量的对象
c、 移动(拖动数据[“项”]、增量x、增量y)
#记录新位置
拖动数据[“x”]=event.x
拖动数据[“y”]=event.y
#设置画布和图像
root=Tk()
c=画布(根,宽=800,高=600)
c、 包()
test=ImageTk.PhotoImage(Image.open(“test.png”))
c、 创建图像(400300,图像=测试,标记=“基本”)
refs=[]#用于保留对函数中使用的图像的引用
#绑定鼠标键
c、 标签绑定(“基本”、“基本”按钮,按OnBaseButtonPress)
c、 标记绑定(“基本”、“OnBaseButtonRelease”)
c、 标记绑定(“基础”、“基础”、“OnBaseMotion”)
拖动_数据={“x”:0,“y”:0,“项”:无}
mainloop()
您可以获取项目类型()、项目配置()等

然后,您可以重新创建相同的对象


另请参见:

Hi faf。这个问题有点简短和模糊。请提供尽可能多的信息。如果你想要代码,一定要包括你已经尝试过的代码,以及为什么它不能按你想要的方式工作。请同时阅读。