复制 Tkinter 画布项目 [英] Copy Tkinter Canvas Items
问题描述
我需要 top 能够创建 tkinter 画布项目的副本,以便可以从原件中拖出图像的副本.我已经为图像拖动工作,但我似乎无法复制图像项目.任何帮助将不胜感激!谢谢.
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.
抱歉一开始没有包含我的代码.由于给出的答案,我能够解决问题.这是我现在可以使用的代码的精简示例:
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()
推荐答案
您可以获取项目类型 (canvas.type(item)),项目配置(canvas.itemconfig(item)) 等
You can get item type (canvas.type(item)), item configuration (canvas.itemconfig(item)) and etc.
而且你可以重新创建相同的对象.
And than you can recreate identical object.
这篇关于复制 Tkinter 画布项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!