python - 复制 Tkinter Canvas 项目

标签 python tkinter

我需要能够创建 tkinter Canvas 项目的副本,以便可以将图像的副本从原始图像中拖出。我对图像进行了拖动操作,但我似乎无法复制图像项目。任何帮助将不胜感激!谢谢。

编辑:抱歉一开始没有包含我的代码。由于给出的答案,我能够解决这个问题。这是我现在可以使用的代码的精简示例:

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) ,等等

然后您可以重新创建一个相同的对象。

另请参阅:Tkinter - making a second canvas display the contents of another .

关于python - 复制 Tkinter Canvas 项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20275893/

相关文章:

python - heroku:无法检测到此应用程序的默认语言

python - 导入错误 : No module named 'spiders'

python - 在 gui 中更新 matplotlib 图的有效方法?

python - python-在默认程序中打开wav文件(Linux)

Python Tkinter 按钮没有出现?

python - 通过鼠标点击从板上选择方 block 的有效方法(Python 3.X.tkinter)

python - 将 Node.js 脚本移植到 Python

Python 正则表达式 : Formatting use of commas, 国际句点

python - 安排脚本每天运行并存储数据 AWS

python - 如何使用 TkInter 填充或扩展函数与 self?